index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.RegistryConfig;
import java.util.Map;
/**
* This is a builder for build {@link RegistryConfig}.
*
* @since 2.7
*/
public class RegistryBuilder extends AbstractBuilder<RegistryConfig, RegistryBuilder> {
/**
* Register center address
*/
private String address;
/**
* Username to login register center
*/
private String username;
/**
* Password to login register center
*/
private String password;
/**
* Default port for register center
*/
private Integer port;
/**
* Protocol for register center
*/
private String protocol;
/**
* Network transmission type
*/
private String transporter;
private String server;
private String client;
private String cluster;
/**
* The group the services registry in
*/
private String group;
private String version;
/**
* Request timeout in milliseconds for register center
*/
private Integer timeout;
/**
* Session timeout in milliseconds for register center
*/
private Integer session;
/**
* File for saving register center dynamic list
*/
private String file;
/**
* Wait time before stop
*/
private Integer wait;
/**
* Whether to check if register center is available when boot up
*/
private Boolean check;
/**
* Whether to allow dynamic service to register on the register center
*/
private Boolean dynamic;
/**
* Whether to export service on the register center
*/
private Boolean register;
/**
* Whether allow to subscribe service on the register center
*/
private Boolean subscribe;
/**
* The customized parameters
*/
private Map<String, String> parameters;
/**
* Whether it's default
*/
private Boolean isDefault;
/**
* Simple the registry. both useful for provider and consumer
*
* @since 2.7.0
*/
private Boolean simplified;
/**
* After simplify the registry, should add some parameter individually. just for provider.
* <p>
* such as: extra-keys = A,b,c,d
*
* @since 2.7.0
*/
private String extraKeys;
/**
* the address work as config center or not
*/
private Boolean useAsConfigCenter;
/**
* the address work as remote metadata center or not
*/
private Boolean useAsMetadataCenter;
/**
* list of rpc protocols accepted by this registry, for example, "dubbo,rest"
*/
private String accepts;
/**
* Always use this registry first if set to true, useful when subscribe to multiple registries
*/
private Boolean preferred;
/**
* Affects traffic distribution among registries, useful when subscribe to multiple registries
* Take effect only when no preferred registry is specified.
*/
private Integer weight;
public static RegistryBuilder newBuilder() {
return new RegistryBuilder();
}
public RegistryBuilder id(String id) {
return super.id(id);
}
public RegistryBuilder address(String address) {
this.address = address;
return getThis();
}
public RegistryBuilder username(String username) {
this.username = username;
return getThis();
}
public RegistryBuilder password(String password) {
this.password = password;
return getThis();
}
public RegistryBuilder port(Integer port) {
this.port = port;
return getThis();
}
public RegistryBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public RegistryBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
/**
* @param transport
* @see #transporter(String)
* @deprecated
*/
@Deprecated
public RegistryBuilder transport(String transport) {
this.transporter = transport;
return getThis();
}
public RegistryBuilder server(String server) {
this.server = server;
return getThis();
}
public RegistryBuilder client(String client) {
this.client = client;
return getThis();
}
public RegistryBuilder cluster(String cluster) {
this.cluster = cluster;
return getThis();
}
public RegistryBuilder group(String group) {
this.group = group;
return getThis();
}
public RegistryBuilder version(String version) {
this.version = version;
return getThis();
}
public RegistryBuilder timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
}
public RegistryBuilder session(Integer session) {
this.session = session;
return getThis();
}
public RegistryBuilder file(String file) {
this.file = file;
return getThis();
}
/**
* @param wait
* @see ProviderBuilder#wait(Integer)
* @deprecated
*/
@Deprecated
public RegistryBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
}
public RegistryBuilder isCheck(Boolean check) {
this.check = check;
return getThis();
}
public RegistryBuilder isDynamic(Boolean dynamic) {
this.dynamic = dynamic;
return getThis();
}
public RegistryBuilder register(Boolean register) {
this.register = register;
return getThis();
}
public RegistryBuilder subscribe(Boolean subscribe) {
this.subscribe = subscribe;
return getThis();
}
public RegistryBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
/**
* @param name the parameter name
* @param value the parameter value
* @return {@link RegistryBuilder}
* @since 2.7.8
*/
public RegistryBuilder parameter(String name, String value) {
return appendParameter(name, value);
}
public RegistryBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public RegistryBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public RegistryBuilder simplified(Boolean simplified) {
this.simplified = simplified;
return getThis();
}
public RegistryBuilder extraKeys(String extraKeys) {
this.extraKeys = extraKeys;
return getThis();
}
public RegistryBuilder useAsConfigCenter(Boolean useAsConfigCenter) {
this.useAsConfigCenter = useAsConfigCenter;
return getThis();
}
public RegistryBuilder useAsMetadataCenter(Boolean useAsMetadataCenter) {
this.useAsMetadataCenter = useAsMetadataCenter;
return getThis();
}
public RegistryBuilder preferred(Boolean preferred) {
this.preferred = preferred;
return getThis();
}
public RegistryBuilder accepts(String accepts) {
this.accepts = accepts;
return getThis();
}
public RegistryBuilder weight(Integer weight) {
this.weight = weight;
return getThis();
}
public RegistryConfig build() {
RegistryConfig registry = new RegistryConfig();
super.build(registry);
registry.setCheck(check);
registry.setClient(client);
registry.setCluster(cluster);
registry.setDefault(isDefault);
registry.setDynamic(dynamic);
registry.setExtraKeys(extraKeys);
registry.setFile(file);
registry.setGroup(group);
registry.setParameters(parameters);
registry.setPassword(password);
registry.setPort(port);
registry.setProtocol(protocol);
registry.setRegister(register);
registry.setServer(server);
registry.setSession(session);
registry.setSimplified(simplified);
registry.setSubscribe(subscribe);
registry.setTimeout(timeout);
registry.setTransporter(transporter);
registry.setUsername(username);
registry.setVersion(version);
registry.setWait(wait);
registry.setUseAsConfigCenter(useAsConfigCenter);
registry.setUseAsMetadataCenter(useAsMetadataCenter);
registry.setAccepts(accepts);
registry.setPreferred(preferred);
registry.setWeight(weight);
registry.setAddress(address);
return registry;
}
@Override
protected RegistryBuilder getThis() {
return this;
}
}
| 8,600 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractMethodConfig;
import java.util.Map;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractMethodBuilder<T extends AbstractMethodConfig, B extends AbstractMethodBuilder<T, B>>
extends AbstractBuilder<T, B> {
/**
* The timeout for remote invocation in milliseconds
*/
protected Integer timeout;
/**
* The retry times
*/
protected Integer retries;
/**
* max concurrent invocations
*/
protected Integer actives;
/**
* The load balance
*/
protected String loadbalance;
/**
* Whether to async
* note that: it is an unreliable asynchronism that ignores return values and does not block threads.
*/
protected Boolean async;
/**
* Whether to ack async-sent
*/
protected Boolean sent;
/**
* The name of mock class which gets called when a service fails to execute
*
* note that: the mock doesn't support on the provider side,and the mock is executed when a non-business exception
* occurs after a remote service call
*/
protected String mock;
/**
* Merger
*/
protected String merger;
/**
* Cache the return result with the call parameter as key, the following options are available: lru, threadlocal,
* jcache, etc.
*/
protected String cache;
/**
* Whether JSR303 standard annotation validation is enabled or not, if enabled, annotations on method parameters will
* be validated
*/
protected String validation;
/**
* The customized parameters
*/
protected Map<String, String> parameters;
/**
* Forks for forking cluster
*/
protected Integer forks;
public B timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
}
public B retries(Integer retries) {
this.retries = retries;
return getThis();
}
public B actives(Integer actives) {
this.actives = actives;
return getThis();
}
public B loadbalance(String loadbalance) {
this.loadbalance = loadbalance;
return getThis();
}
public B async(Boolean async) {
this.async = async;
return getThis();
}
public B sent(Boolean sent) {
this.sent = sent;
return getThis();
}
public B mock(String mock) {
this.mock = mock;
return getThis();
}
public B mock(Boolean mock) {
if (mock != null) {
this.mock = mock.toString();
} else {
this.mock = null;
}
return getThis();
}
public B merger(String merger) {
this.merger = merger;
return getThis();
}
public B cache(String cache) {
this.cache = cache;
return getThis();
}
public B validation(String validation) {
this.validation = validation;
return getThis();
}
public B appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public B appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public B forks(Integer forks) {
this.forks = forks;
return getThis();
}
@Override
@SuppressWarnings("unchecked")
public void build(T instance) {
super.build(instance);
if (actives != null) {
instance.setActives(actives);
}
if (async != null) {
instance.setAsync(async);
}
if (!StringUtils.isEmpty(cache)) {
instance.setCache(cache);
}
if (forks != null) {
instance.setForks(forks);
}
if (!StringUtils.isEmpty(loadbalance)) {
instance.setLoadbalance(loadbalance);
}
if (!StringUtils.isEmpty(merger)) {
instance.setMerger(merger);
}
if (!StringUtils.isEmpty(mock)) {
instance.setMock(mock);
}
if (retries != null) {
instance.setRetries(retries);
}
if (sent != null) {
instance.setSent(sent);
}
if (timeout != null) {
instance.setTimeout(timeout);
}
if (!StringUtils.isEmpty(validation)) {
instance.setValidation(validation);
}
if (parameters != null) {
instance.setParameters(parameters);
}
}
}
| 8,601 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.util.ArrayList;
import java.util.List;
/**
* This is a builder for build {@link ModuleConfig}.
*
* @since 2.7
*/
public class ModuleBuilder extends AbstractBuilder<ModuleConfig, ModuleBuilder> {
/**
* Module name
*/
private String name;
/**
* Module version
*/
private String version;
/**
* Module owner
*/
private String owner;
/**
* Module's organization
*/
private String organization;
/**
* Registry centers
*/
private List<RegistryConfig> registries;
/**
* Monitor center
*/
private MonitorConfig monitor;
/**
* If it's default
*/
private Boolean isDefault;
public ModuleBuilder name(String name) {
this.name = name;
return getThis();
}
public ModuleBuilder version(String version) {
this.version = version;
return getThis();
}
public ModuleBuilder owner(String owner) {
this.owner = owner;
return getThis();
}
public ModuleBuilder organization(String organization) {
this.organization = organization;
return getThis();
}
public ModuleBuilder addRegistries(List<? extends RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
}
public ModuleBuilder addRegistry(RegistryConfig registry) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.add(registry);
return getThis();
}
public ModuleBuilder monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
}
public ModuleBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ModuleConfig build() {
ModuleConfig moduleConfig = new ModuleConfig();
super.build(moduleConfig);
moduleConfig.setDefault(isDefault);
moduleConfig.setMonitor(monitor);
moduleConfig.setName(name);
moduleConfig.setOrganization(organization);
moduleConfig.setOwner(owner);
moduleConfig.setRegistries(registries);
moduleConfig.setVersion(version);
return moduleConfig;
}
@Override
protected ModuleBuilder getThis() {
return this;
}
}
| 8,602 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.MonitorConfig;
import java.util.Map;
/**
* This is a builder for build {@link MonitorConfig}.
*
* @since 2.7
*/
public class MonitorBuilder extends AbstractBuilder<MonitorConfig, MonitorBuilder> {
/**
* The protocol of the monitor, if the value is registry, it will search the monitor address from the registry center,
* otherwise, it will directly connect to the monitor center
*/
private String protocol;
/**
* The monitor address
*/
private String address;
/**
* The monitor user name
*/
private String username;
/**
* The password
*/
private String password;
private String group;
private String version;
private String interval;
/**
* customized parameters
*/
private Map<String, String> parameters;
/**
* If it's default
*/
private Boolean isDefault;
public MonitorBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public MonitorBuilder address(String address) {
this.address = address;
return getThis();
}
public MonitorBuilder username(String username) {
this.username = username;
return getThis();
}
public MonitorBuilder password(String password) {
this.password = password;
return getThis();
}
public MonitorBuilder group(String group) {
this.group = group;
return getThis();
}
public MonitorBuilder version(String version) {
this.version = version;
return getThis();
}
public MonitorBuilder interval(String interval) {
this.interval = interval;
return getThis();
}
public MonitorBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public MonitorBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public MonitorBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public MonitorConfig build() {
MonitorConfig monitorConfig = new MonitorConfig();
super.build(monitorConfig);
monitorConfig.setProtocol(protocol);
monitorConfig.setAddress(address);
monitorConfig.setUsername(username);
monitorConfig.setPassword(password);
monitorConfig.setGroup(group);
monitorConfig.setVersion(version);
monitorConfig.setInterval(interval);
monitorConfig.setParameters(parameters);
monitorConfig.setDefault(isDefault);
return monitorConfig;
}
@Override
protected MonitorBuilder getThis() {
return this;
}
}
| 8,603 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/package-info.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A bunch of builder classes to facilitate programming of raw API.
* TODO, these are experimental APIs and are possible to change at any time before marked as production.
*/
package org.apache.dubbo.config.bootstrap.builders;
| 8,604 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.deploy.AbstractDeployer;
import org.apache.dubbo.common.deploy.ApplicationDeployListener;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployListener;
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.lang.ShutdownHookCallbacks;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.DubboShutdownHook;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.utils.CompositeReferenceCache;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.metadata.report.MetadataReportFactory;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.metrics.collector.DefaultMetricsCollector;
import org.apache.dubbo.metrics.config.event.ConfigCenterEvent;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory;
import org.apache.dubbo.metrics.report.MetricsReporter;
import org.apache.dubbo.metrics.report.MetricsReporterFactory;
import org.apache.dubbo.metrics.service.MetricsServiceExporter;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
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.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXECUTE_DESTROY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_INIT_CONFIG_CENTER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REFRESH_INSTANCE_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REGISTER_INSTANCE_ERROR;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_METADATA_PUBLISH_DELAY;
import static org.apache.dubbo.metadata.MetadataConstants.METADATA_PUBLISH_DELAY_KEY;
import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
/**
* initialize and start application instance
*/
public class DefaultApplicationDeployer extends AbstractDeployer<ApplicationModel> implements ApplicationDeployer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DefaultApplicationDeployer.class);
private final ApplicationModel applicationModel;
private final ConfigManager configManager;
private final Environment environment;
private final ReferenceCache referenceCache;
private final FrameworkExecutorRepository frameworkExecutorRepository;
private final ExecutorRepository executorRepository;
private final AtomicBoolean hasPreparedApplicationInstance = new AtomicBoolean(false);
private volatile boolean hasPreparedInternalModule = false;
private ScheduledFuture<?> asyncMetadataFuture;
private volatile CompletableFuture<Boolean> startFuture;
private final DubboShutdownHook dubboShutdownHook;
private volatile MetricsServiceExporter metricsServiceExporter;
private final Object stateLock = new Object();
private final Object startLock = new Object();
private final Object destroyLock = new Object();
private final Object internalModuleLock = new Object();
public DefaultApplicationDeployer(ApplicationModel applicationModel) {
super(applicationModel);
this.applicationModel = applicationModel;
configManager = applicationModel.getApplicationConfigManager();
environment = applicationModel.modelEnvironment();
referenceCache = new CompositeReferenceCache(applicationModel);
frameworkExecutorRepository =
applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class);
executorRepository = ExecutorRepository.getInstance(applicationModel);
dubboShutdownHook = new DubboShutdownHook(applicationModel);
// load spi listener
Set<ApplicationDeployListener> deployListeners = applicationModel
.getExtensionLoader(ApplicationDeployListener.class)
.getSupportedExtensionInstances();
for (ApplicationDeployListener listener : deployListeners) {
this.addDeployListener(listener);
}
}
public static ApplicationDeployer get(ScopeModel moduleOrApplicationModel) {
ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(moduleOrApplicationModel);
ApplicationDeployer applicationDeployer = applicationModel.getDeployer();
if (applicationDeployer == null) {
applicationDeployer = applicationModel.getBeanFactory().getOrRegisterBean(DefaultApplicationDeployer.class);
}
return applicationDeployer;
}
@Override
public ApplicationModel getApplicationModel() {
return applicationModel;
}
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
return applicationModel.getExtensionLoader(type);
}
private void unRegisterShutdownHook() {
dubboShutdownHook.unregister();
}
/**
* Close registration of instance for pure Consumer process by setting registerConsumer to 'false'
* by default is true.
*/
private boolean isRegisterConsumerInstance() {
Boolean registerConsumer = getApplication().getRegisterConsumer();
if (registerConsumer == null) {
return true;
}
return Boolean.TRUE.equals(registerConsumer);
}
@Override
public ReferenceCache getReferenceCache() {
return referenceCache;
}
/**
* Initialize
*/
@Override
public void initialize() {
if (initialized) {
return;
}
// Ensure that the initialization is completed when concurrent calls
synchronized (startLock) {
if (initialized) {
return;
}
onInitialize();
// register shutdown hook
registerShutdownHook();
startConfigCenter();
loadApplicationConfigs();
initModuleDeployers();
initMetricsReporter();
initMetricsService();
// @since 2.7.8
startMetadataCenter();
initialized = true;
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " has been initialized!");
}
}
}
private void registerShutdownHook() {
dubboShutdownHook.register();
}
private void initModuleDeployers() {
// make sure created default module
applicationModel.getDefaultModule();
// deployer initialize
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().initialize();
}
}
private void loadApplicationConfigs() {
configManager.loadConfigs();
}
private void startConfigCenter() {
// load application config
configManager.loadConfigsOfTypeFromProps(ApplicationConfig.class);
// try set model name
if (StringUtils.isBlank(applicationModel.getModelName())) {
applicationModel.setModelName(applicationModel.tryGetApplicationName());
}
// load config centers
configManager.loadConfigsOfTypeFromProps(ConfigCenterConfig.class);
useRegistryAsConfigCenterIfNecessary();
// check Config Center
Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters();
if (CollectionUtils.isEmpty(configCenters)) {
ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
configCenterConfig.setScopeModel(applicationModel);
configCenterConfig.refresh();
ConfigValidationUtils.validateConfigCenterConfig(configCenterConfig);
if (configCenterConfig.isValid()) {
configManager.addConfigCenter(configCenterConfig);
configCenters = configManager.getConfigCenters();
}
} else {
for (ConfigCenterConfig configCenterConfig : configCenters) {
configCenterConfig.refresh();
ConfigValidationUtils.validateConfigCenterConfig(configCenterConfig);
}
}
if (CollectionUtils.isNotEmpty(configCenters)) {
CompositeDynamicConfiguration compositeDynamicConfiguration = new CompositeDynamicConfiguration();
for (ConfigCenterConfig configCenter : configCenters) {
// Pass config from ConfigCenterBean to environment
environment.updateExternalConfigMap(configCenter.getExternalConfiguration());
environment.updateAppExternalConfigMap(configCenter.getAppExternalConfiguration());
// Fetch config from remote config center
compositeDynamicConfiguration.addConfiguration(prepareEnvironment(configCenter));
}
environment.setDynamicConfiguration(compositeDynamicConfiguration);
}
}
private void startMetadataCenter() {
useRegistryAsMetadataCenterIfNecessary();
ApplicationConfig applicationConfig = getApplication();
String metadataType = applicationConfig.getMetadataType();
// FIXME, multiple metadata config support.
Collection<MetadataReportConfig> metadataReportConfigs = configManager.getMetadataConfigs();
if (CollectionUtils.isEmpty(metadataReportConfigs)) {
if (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
throw new IllegalStateException(
"No MetadataConfig found, Metadata Center address is required when 'metadata=remote' is enabled.");
}
return;
}
MetadataReportInstance metadataReportInstance =
applicationModel.getBeanFactory().getBean(MetadataReportInstance.class);
List<MetadataReportConfig> validMetadataReportConfigs = new ArrayList<>(metadataReportConfigs.size());
for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) {
if (ConfigValidationUtils.isValidMetadataConfig(metadataReportConfig)) {
ConfigValidationUtils.validateMetadataConfig(metadataReportConfig);
validMetadataReportConfigs.add(metadataReportConfig);
}
}
metadataReportInstance.init(validMetadataReportConfigs);
if (!metadataReportInstance.inited()) {
throw new IllegalStateException(String.format(
"%s MetadataConfigs found, but none of them is valid.", metadataReportConfigs.size()));
}
}
/**
* For compatibility purpose, use registry as the default config center when
* there's no config center specified explicitly and
* useAsConfigCenter of registryConfig is null or true
*/
private void useRegistryAsConfigCenterIfNecessary() {
// we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated.
if (environment.getDynamicConfiguration().isPresent()) {
return;
}
if (CollectionUtils.isNotEmpty(configManager.getConfigCenters())) {
return;
}
// load registry
configManager.loadConfigsOfTypeFromProps(RegistryConfig.class);
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
if (defaultRegistries.size() > 0) {
defaultRegistries.stream()
.filter(this::isUsedRegistryAsConfigCenter)
.map(this::registryAsConfigCenter)
.forEach(configCenter -> {
if (configManager.getConfigCenter(configCenter.getId()).isPresent()) {
return;
}
configManager.addConfigCenter(configCenter);
logger.info("use registry as config-center: " + configCenter);
});
}
}
private void initMetricsService() {
this.metricsServiceExporter =
getExtensionLoader(MetricsServiceExporter.class).getDefaultExtension();
metricsServiceExporter.init();
}
private void initMetricsReporter() {
if (!isSupportMetrics()) {
return;
}
DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class);
Optional<MetricsConfig> configOptional = configManager.getMetrics();
// If no specific metrics type is configured and there is no Prometheus dependency in the dependencies.
MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel));
if (StringUtils.isBlank(metricsConfig.getProtocol())) {
metricsConfig.setProtocol(isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT);
}
collector.setCollectEnabled(true);
collector.collectApplication();
collector.setThreadpoolCollectEnabled(
Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true));
collector.setMetricsInitEnabled(
Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true));
MetricsReporterFactory metricsReporterFactory =
getExtensionLoader(MetricsReporterFactory.class).getAdaptiveExtension();
MetricsReporter metricsReporter = null;
try {
metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl());
} catch (IllegalStateException e) {
if (e.getMessage().startsWith("No such extension org.apache.dubbo.metrics.report.MetricsReporterFactory")) {
logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", e.getMessage());
return;
} else {
throw e;
}
}
metricsReporter.init();
applicationModel.getBeanFactory().registerBean(metricsReporter);
// If the protocol is not the default protocol, the default protocol is also initialized.
if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) {
DefaultMetricsReporterFactory defaultMetricsReporterFactory =
new DefaultMetricsReporterFactory(applicationModel);
MetricsReporter defaultMetricsReporter =
defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl());
defaultMetricsReporter.init();
applicationModel.getBeanFactory().registerBean(defaultMetricsReporter);
}
}
public boolean isSupportMetrics() {
return isClassPresent("io.micrometer.core.instrument.MeterRegistry");
}
public static boolean isSupportPrometheus() {
return isClassPresent("io.micrometer.prometheus.PrometheusConfig")
&& isClassPresent("io.prometheus.client.exporter.BasicAuthHttpConnectionFactory")
&& isClassPresent("io.prometheus.client.exporter.HttpConnectionFactory")
&& isClassPresent("io.prometheus.client.exporter.PushGateway");
}
private static boolean isClassPresent(String className) {
return ClassUtils.isPresent(className, DefaultApplicationDeployer.class.getClassLoader());
}
private boolean isUsedRegistryAsConfigCenter(RegistryConfig registryConfig) {
return isUsedRegistryAsCenter(
registryConfig, registryConfig::getUseAsConfigCenter, "config", DynamicConfigurationFactory.class);
}
private ConfigCenterConfig registryAsConfigCenter(RegistryConfig registryConfig) {
String protocol = registryConfig.getProtocol();
Integer port = registryConfig.getPort();
URL url = URL.valueOf(registryConfig.getAddress(), registryConfig.getScopeModel());
String id = "config-center-" + protocol + "-" + url.getHost() + "-" + port;
ConfigCenterConfig cc = new ConfigCenterConfig();
cc.setId(id);
cc.setScopeModel(applicationModel);
if (cc.getParameters() == null) {
cc.setParameters(new HashMap<>());
}
if (CollectionUtils.isNotEmptyMap(registryConfig.getParameters())) {
cc.getParameters().putAll(registryConfig.getParameters()); // copy the parameters
}
cc.getParameters().put(CLIENT_KEY, registryConfig.getClient());
cc.setProtocol(protocol);
cc.setPort(port);
if (StringUtils.isNotEmpty(registryConfig.getGroup())) {
cc.setGroup(registryConfig.getGroup());
}
cc.setAddress(getRegistryCompatibleAddress(registryConfig));
cc.setNamespace(registryConfig.getGroup());
cc.setUsername(registryConfig.getUsername());
cc.setPassword(registryConfig.getPassword());
if (registryConfig.getTimeout() != null) {
cc.setTimeout(registryConfig.getTimeout().longValue());
}
cc.setHighestPriority(false);
return cc;
}
private void useRegistryAsMetadataCenterIfNecessary() {
Collection<MetadataReportConfig> originMetadataConfigs = configManager.getMetadataConfigs();
if (originMetadataConfigs.stream().anyMatch(m -> Objects.nonNull(m.getAddress()))) {
return;
}
Collection<MetadataReportConfig> metadataConfigsToOverride = originMetadataConfigs.stream()
.filter(m -> Objects.isNull(m.getAddress()))
.collect(Collectors.toList());
if (metadataConfigsToOverride.size() > 1) {
return;
}
MetadataReportConfig metadataConfigToOverride =
metadataConfigsToOverride.stream().findFirst().orElse(null);
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
if (!defaultRegistries.isEmpty()) {
defaultRegistries.stream()
.filter(this::isUsedRegistryAsMetadataCenter)
.map(registryConfig -> registryAsMetadataCenter(registryConfig, metadataConfigToOverride))
.forEach(metadataReportConfig -> {
overrideMetadataReportConfig(metadataConfigToOverride, metadataReportConfig);
});
}
}
private void overrideMetadataReportConfig(
MetadataReportConfig metadataConfigToOverride, MetadataReportConfig metadataReportConfig) {
if (metadataReportConfig.getId() == null) {
Collection<MetadataReportConfig> metadataReportConfigs = configManager.getMetadataConfigs();
if (CollectionUtils.isNotEmpty(metadataReportConfigs)) {
for (MetadataReportConfig existedConfig : metadataReportConfigs) {
if (existedConfig.getId() == null
&& existedConfig.getAddress().equals(metadataReportConfig.getAddress())) {
return;
}
}
}
configManager.removeConfig(metadataConfigToOverride);
configManager.addMetadataReport(metadataReportConfig);
} else {
Optional<MetadataReportConfig> configOptional =
configManager.getConfig(MetadataReportConfig.class, metadataReportConfig.getId());
if (configOptional.isPresent()) {
return;
}
configManager.removeConfig(metadataConfigToOverride);
configManager.addMetadataReport(metadataReportConfig);
}
logger.info("use registry as metadata-center: " + metadataReportConfig);
}
private boolean isUsedRegistryAsMetadataCenter(RegistryConfig registryConfig) {
return isUsedRegistryAsCenter(
registryConfig, registryConfig::getUseAsMetadataCenter, "metadata", MetadataReportFactory.class);
}
/**
* Is used the specified registry as a center infrastructure
*
* @param registryConfig the {@link RegistryConfig}
* @param usedRegistryAsCenter the configured value on
* @param centerType the type name of center
* @param extensionClass an extension class of a center infrastructure
* @return
* @since 2.7.8
*/
private boolean isUsedRegistryAsCenter(
RegistryConfig registryConfig,
Supplier<Boolean> usedRegistryAsCenter,
String centerType,
Class<?> extensionClass) {
final boolean supported;
Boolean configuredValue = usedRegistryAsCenter.get();
if (configuredValue != null) { // If configured, take its value.
supported = configuredValue.booleanValue();
} else { // Or check the extension existence
String protocol = registryConfig.getProtocol();
supported = supportsExtension(extensionClass, protocol);
if (logger.isInfoEnabled()) {
logger.info(format(
"No value is configured in the registry, the %s extension[name : %s] %s as the %s center",
extensionClass.getSimpleName(),
protocol,
supported ? "supports" : "does not support",
centerType));
}
}
if (logger.isInfoEnabled()) {
logger.info(format(
"The registry[%s] will be %s as the %s center",
registryConfig, supported ? "used" : "not used", centerType));
}
return supported;
}
/**
* Supports the extension with the specified class and name
*
* @param extensionClass the {@link Class} of extension
* @param name the name of extension
* @return if supports, return <code>true</code>, or <code>false</code>
* @since 2.7.8
*/
private boolean supportsExtension(Class<?> extensionClass, String name) {
if (isNotEmpty(name)) {
ExtensionLoader<?> extensionLoader = getExtensionLoader(extensionClass);
return extensionLoader.hasExtension(name);
}
return false;
}
private MetadataReportConfig registryAsMetadataCenter(
RegistryConfig registryConfig, MetadataReportConfig originMetadataReportConfig) {
MetadataReportConfig metadataReportConfig = originMetadataReportConfig == null
? new MetadataReportConfig(registryConfig.getApplicationModel())
: originMetadataReportConfig;
if (metadataReportConfig.getId() == null) {
metadataReportConfig.setId(registryConfig.getId());
}
metadataReportConfig.setScopeModel(applicationModel);
if (metadataReportConfig.getParameters() == null) {
metadataReportConfig.setParameters(new HashMap<>());
}
if (CollectionUtils.isNotEmptyMap(registryConfig.getParameters())) {
for (Map.Entry<String, String> entry :
registryConfig.getParameters().entrySet()) {
metadataReportConfig
.getParameters()
.putIfAbsent(entry.getKey(), entry.getValue()); // copy the parameters
}
}
metadataReportConfig.getParameters().put(CLIENT_KEY, registryConfig.getClient());
if (metadataReportConfig.getGroup() == null) {
metadataReportConfig.setGroup(registryConfig.getGroup());
}
if (metadataReportConfig.getAddress() == null) {
metadataReportConfig.setAddress(getRegistryCompatibleAddress(registryConfig));
}
if (metadataReportConfig.getUsername() == null) {
metadataReportConfig.setUsername(registryConfig.getUsername());
}
if (metadataReportConfig.getPassword() == null) {
metadataReportConfig.setPassword(registryConfig.getPassword());
}
if (metadataReportConfig.getTimeout() == null) {
metadataReportConfig.setTimeout(registryConfig.getTimeout());
}
return metadataReportConfig;
}
private String getRegistryCompatibleAddress(RegistryConfig registryConfig) {
String registryAddress = registryConfig.getAddress();
String[] addresses = REGISTRY_SPLIT_PATTERN.split(registryAddress);
if (ArrayUtils.isEmpty(addresses)) {
throw new IllegalStateException("Invalid registry address found.");
}
String address = addresses[0];
// since 2.7.8
// Issue : https://github.com/apache/dubbo/issues/6476
StringBuilder metadataAddressBuilder = new StringBuilder();
URL url = URL.valueOf(address, registryConfig.getScopeModel());
String protocolFromAddress = url.getProtocol();
if (isEmpty(protocolFromAddress)) {
// If the protocol from address is missing, is like :
// "dubbo.registry.address = 127.0.0.1:2181"
String protocolFromConfig = registryConfig.getProtocol();
metadataAddressBuilder.append(protocolFromConfig).append("://");
}
metadataAddressBuilder.append(address);
return metadataAddressBuilder.toString();
}
/**
* Start the bootstrap
*
* @return
*/
@Override
public Future start() {
synchronized (startLock) {
if (isStopping() || isStopped() || isFailed()) {
throw new IllegalStateException(getIdentifier() + " is stopping or stopped, can not start again");
}
try {
// maybe call start again after add new module, check if any new module
boolean hasPendingModule = hasPendingModule();
if (isStarting()) {
// currently, is starting, maybe both start by module and application
// if it has new modules, start them
if (hasPendingModule) {
startModules();
}
// if it is starting, reuse previous startFuture
return startFuture;
}
// if is started and no new module, just return
if (isStarted() && !hasPendingModule) {
return CompletableFuture.completedFuture(false);
}
// pending -> starting : first start app
// started -> starting : re-start app
onStarting();
initialize();
doStart();
} catch (Throwable e) {
onFailed(getIdentifier() + " start failure", e);
throw e;
}
return startFuture;
}
}
private boolean hasPendingModule() {
boolean found = false;
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.getDeployer().isPending()) {
found = true;
break;
}
}
return found;
}
@Override
public Future getStartFuture() {
return startFuture;
}
private void doStart() {
startModules();
// prepare application instance
// prepareApplicationInstance();
// Ignore checking new module after start
// executorRepository.getSharedExecutor().submit(() -> {
// try {
// while (isStarting()) {
// // notify when any module state changed
// synchronized (stateLock) {
// try {
// stateLock.wait(500);
// } catch (InterruptedException e) {
// // ignore
// }
// }
//
// // if has new module, do start again
// if (hasPendingModule()) {
// startModules();
// }
// }
// } catch (Throwable e) {
// onFailed(getIdentifier() + " check start occurred an exception", e);
// }
// });
}
private void startModules() {
// ensure init and start internal module first
prepareInternalModule();
// filter and start pending modules, ignore new module during starting, throw exception of module start
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.getDeployer().isPending()) {
moduleModel.getDeployer().start();
}
}
}
@Override
public void prepareApplicationInstance() {
if (hasPreparedApplicationInstance.get()) {
return;
}
// export MetricsService
exportMetricsService();
if (isRegisterConsumerInstance()) {
exportMetadataService();
if (hasPreparedApplicationInstance.compareAndSet(false, true)) {
// register the local ServiceInstance if required
registerServiceInstance();
}
}
}
public void prepareInternalModule() {
if (hasPreparedInternalModule) {
return;
}
synchronized (internalModuleLock) {
if (hasPreparedInternalModule) {
return;
}
// start internal module
ModuleDeployer internalModuleDeployer =
applicationModel.getInternalModule().getDeployer();
if (!internalModuleDeployer.isStarted()) {
Future future = internalModuleDeployer.start();
// wait for internal module startup
try {
future.get(5, TimeUnit.SECONDS);
hasPreparedInternalModule = true;
} catch (Exception e) {
logger.warn(
CONFIG_FAILED_START_MODEL,
"",
"",
"wait for internal module startup failed: " + e.getMessage(),
e);
}
}
}
}
private void exportMetricsService() {
boolean exportMetrics = applicationModel
.getApplicationConfigManager()
.getMetrics()
.map(MetricsConfig::getExportMetricsService)
.orElse(true);
if (exportMetrics) {
try {
metricsServiceExporter.export();
} catch (Exception e) {
logger.error(
LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION,
"",
"",
"exportMetricsService an exception occurred when handle starting event",
e);
}
}
}
private void unexportMetricsService() {
if (metricsServiceExporter != null) {
try {
metricsServiceExporter.unexport();
} catch (Exception ignored) {
// ignored
}
}
}
private boolean hasExportedServices() {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (CollectionUtils.isNotEmpty(moduleModel.getConfigManager().getServices())) {
return true;
}
}
return false;
}
@Override
public boolean isBackground() {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.getDeployer().isBackground()) {
return true;
}
}
return false;
}
private DynamicConfiguration prepareEnvironment(ConfigCenterConfig configCenter) {
if (configCenter.isValid()) {
if (!configCenter.checkOrUpdateInitialized(true)) {
return null;
}
DynamicConfiguration dynamicConfiguration;
try {
dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl());
} catch (Exception e) {
if (!configCenter.isCheck()) {
logger.warn(
CONFIG_FAILED_INIT_CONFIG_CENTER,
"",
"",
"The configuration center failed to initialize",
e);
configCenter.setInitialized(false);
return null;
} else {
throw new IllegalStateException(e);
}
}
ApplicationModel applicationModel = getApplicationModel();
if (StringUtils.isNotEmpty(configCenter.getConfigFile())) {
String configContent =
dynamicConfiguration.getProperties(configCenter.getConfigFile(), configCenter.getGroup());
if (StringUtils.isNotEmpty(configContent)) {
logger.info(String.format(
"Got global remote configuration from config center with key-%s and group-%s: \n %s",
configCenter.getConfigFile(), configCenter.getGroup(), configContent));
}
String appGroup = getApplication().getName();
String appConfigContent = null;
String appConfigFile = null;
if (isNotEmpty(appGroup)) {
appConfigFile = isNotEmpty(configCenter.getAppConfigFile())
? configCenter.getAppConfigFile()
: configCenter.getConfigFile();
appConfigContent = dynamicConfiguration.getProperties(appConfigFile, appGroup);
if (StringUtils.isNotEmpty(appConfigContent)) {
logger.info(String.format(
"Got application specific remote configuration from config center with key %s and group %s: \n %s",
appConfigFile, appGroup, appConfigContent));
}
}
try {
Map<String, String> configMap = parseProperties(configContent);
Map<String, String> appConfigMap = parseProperties(appConfigContent);
environment.updateExternalConfigMap(configMap);
environment.updateAppExternalConfigMap(appConfigMap);
// Add metrics
MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(
applicationModel,
configCenter.getConfigFile(),
configCenter.getGroup(),
configCenter.getProtocol(),
ConfigChangeType.ADDED.name(),
configMap.size()));
if (isNotEmpty(appGroup)) {
MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(
applicationModel,
appConfigFile,
appGroup,
configCenter.getProtocol(),
ConfigChangeType.ADDED.name(),
appConfigMap.size()));
}
} catch (IOException e) {
throw new IllegalStateException("Failed to parse configurations from Config Center.", e);
}
}
return dynamicConfiguration;
}
return null;
}
/**
* Get the instance of {@link DynamicConfiguration} by the specified connection {@link URL} of config-center
*
* @param connectionURL of config-center
* @return non-null
* @since 2.7.5
*/
private DynamicConfiguration getDynamicConfiguration(URL connectionURL) {
String protocol = connectionURL.getProtocol();
DynamicConfigurationFactory factory =
ConfigurationUtils.getDynamicConfigurationFactory(applicationModel, protocol);
return factory.getDynamicConfiguration(connectionURL);
}
private volatile boolean registered;
private final AtomicInteger instanceRefreshScheduleTimes = new AtomicInteger(0);
/**
* Indicate that how many threads are updating service
*/
private final AtomicInteger serviceRefreshState = new AtomicInteger(0);
private void registerServiceInstance() {
try {
registered = true;
ServiceInstanceMetadataUtils.registerMetadataAndInstance(applicationModel);
} catch (Exception e) {
logger.error(
CONFIG_REGISTER_INSTANCE_ERROR,
"configuration server disconnected",
"",
"Register instance error.",
e);
}
if (registered) {
// scheduled task for updating Metadata and ServiceInstance
asyncMetadataFuture = frameworkExecutorRepository
.getSharedScheduledExecutor()
.scheduleWithFixedDelay(
() -> {
// ignore refresh metadata on stopping
if (applicationModel.isDestroyed()) {
return;
}
// refresh for 30 times (default for 30s) when deployer is not started, prevent submit
// too many revision
if (instanceRefreshScheduleTimes.incrementAndGet() % 30 != 0 && !isStarted()) {
return;
}
// refresh for 5 times (default for 5s) when services are being updated by other
// threads, prevent submit too many revision
// note: should not always wait here
if (serviceRefreshState.get() != 0 && instanceRefreshScheduleTimes.get() % 5 != 0) {
return;
}
try {
if (!applicationModel.isDestroyed() && registered) {
ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel);
}
} catch (Exception e) {
if (!applicationModel.isDestroyed()) {
logger.error(
CONFIG_REFRESH_INSTANCE_ERROR,
"",
"",
"Refresh instance and metadata error.",
e);
}
}
},
0,
ConfigurationUtils.get(
applicationModel, METADATA_PUBLISH_DELAY_KEY, DEFAULT_METADATA_PUBLISH_DELAY),
TimeUnit.MILLISECONDS);
}
}
@Override
public void refreshServiceInstance() {
if (registered) {
try {
ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel);
} catch (Exception e) {
logger.error(CONFIG_REFRESH_INSTANCE_ERROR, "", "", "Refresh instance and metadata error.", e);
}
}
}
@Override
public void increaseServiceRefreshCount() {
serviceRefreshState.incrementAndGet();
}
@Override
public void decreaseServiceRefreshCount() {
serviceRefreshState.decrementAndGet();
}
private void unregisterServiceInstance() {
if (registered) {
ServiceInstanceMetadataUtils.unregisterMetadataAndInstance(applicationModel);
}
}
@Override
public void stop() {
applicationModel.destroy();
}
@Override
public void preDestroy() {
synchronized (destroyLock) {
if (isStopping() || isStopped()) {
return;
}
onStopping();
offline();
unregisterServiceInstance();
unexportMetricsService();
unRegisterShutdownHook();
if (asyncMetadataFuture != null) {
asyncMetadataFuture.cancel(true);
}
}
}
private void offline() {
try {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
ModuleServiceRepository serviceRepository = moduleModel.getServiceRepository();
List<ProviderModel> exportedServices = serviceRepository.getExportedServices();
for (ProviderModel exportedService : exportedServices) {
List<ProviderModel.RegisterStatedURL> statedUrls = exportedService.getStatedUrl();
for (ProviderModel.RegisterStatedURL statedURL : statedUrls) {
if (statedURL.isRegistered()) {
doOffline(statedURL);
}
}
}
}
} catch (Throwable t) {
logger.error(
LoggerCodeConstants.INTERNAL_ERROR, "", "", "Exceptions occurred when unregister services.", t);
}
}
private void doOffline(ProviderModel.RegisterStatedURL statedURL) {
RegistryFactory registryFactory = statedURL
.getRegistryUrl()
.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryFactory.class)
.getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl());
registry.unregister(statedURL.getProviderUrl());
statedURL.setRegistered(false);
}
@Override
public void postDestroy() {
synchronized (destroyLock) {
// expect application model is destroyed before here
if (isStopped()) {
return;
}
try {
destroyRegistries();
destroyMetadataReports();
executeShutdownCallbacks();
// TODO should we close unused protocol server which only used by this application?
// protocol server will be closed on all applications of same framework are stopped currently, but no
// associate to application
// see org.apache.dubbo.config.deploy.FrameworkModelCleaner#destroyProtocols
// see
// org.apache.dubbo.config.bootstrap.DubboBootstrapMultiInstanceTest#testMultiProviderApplicationStopOneByOne
// destroy all executor services
destroyExecutorRepository();
onStopped();
} catch (Throwable ex) {
String msg = getIdentifier() + " an error occurred while stopping application: " + ex.getMessage();
onFailed(msg, ex);
}
}
}
private void executeShutdownCallbacks() {
ShutdownHookCallbacks shutdownHookCallbacks =
applicationModel.getBeanFactory().getBean(ShutdownHookCallbacks.class);
shutdownHookCallbacks.callback();
}
@Override
public void notifyModuleChanged(ModuleModel moduleModel, DeployState state) {
checkState(moduleModel, state);
// notify module state changed or module changed
synchronized (stateLock) {
stateLock.notifyAll();
}
}
@Override
public void checkState(ModuleModel moduleModel, DeployState moduleState) {
synchronized (stateLock) {
if (!moduleModel.isInternal() && moduleState == DeployState.STARTED) {
prepareApplicationInstance();
}
DeployState newState = calculateState();
switch (newState) {
case STARTED:
onStarted();
break;
case STARTING:
onStarting();
break;
case STOPPING:
onStopping();
break;
case STOPPED:
onStopped();
break;
case FAILED:
Throwable error = null;
ModuleModel errorModule = null;
for (ModuleModel module : applicationModel.getModuleModels()) {
ModuleDeployer deployer = module.getDeployer();
if (deployer.isFailed() && deployer.getError() != null) {
error = deployer.getError();
errorModule = module;
break;
}
}
onFailed(getIdentifier() + " found failed module: " + errorModule.getDesc(), error);
break;
case PENDING:
// cannot change to pending from other state
// setPending();
break;
}
}
}
private DeployState calculateState() {
DeployState newState = DeployState.UNKNOWN;
int pending = 0, starting = 0, started = 0, stopping = 0, stopped = 0, failed = 0;
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
ModuleDeployer deployer = moduleModel.getDeployer();
if (deployer == null) {
pending++;
} else if (deployer.isPending()) {
pending++;
} else if (deployer.isStarting()) {
starting++;
} else if (deployer.isStarted()) {
started++;
} else if (deployer.isStopping()) {
stopping++;
} else if (deployer.isStopped()) {
stopped++;
} else if (deployer.isFailed()) {
failed++;
}
}
if (failed > 0) {
newState = DeployState.FAILED;
} else if (started > 0) {
if (pending + starting + stopping + stopped == 0) {
// all modules have been started
newState = DeployState.STARTED;
} else if (pending + starting > 0) {
// some module is pending and some is started
newState = DeployState.STARTING;
} else if (stopping + stopped > 0) {
newState = DeployState.STOPPING;
}
} else if (starting > 0) {
// any module is starting
newState = DeployState.STARTING;
} else if (pending > 0) {
if (starting + starting + stopping + stopped == 0) {
// all modules have not starting or started
newState = DeployState.PENDING;
} else if (stopping + stopped > 0) {
// some is pending and some is stopping or stopped
newState = DeployState.STOPPING;
}
} else if (stopping > 0) {
// some is stopping and some stopped
newState = DeployState.STOPPING;
} else if (stopped > 0) {
// all modules are stopped
newState = DeployState.STOPPED;
}
return newState;
}
private void onInitialize() {
for (DeployListener<ApplicationModel> listener : listeners) {
try {
listener.onInitialize(applicationModel);
} catch (Throwable e) {
logger.error(
CONFIG_FAILED_START_MODEL,
"",
"",
getIdentifier() + " an exception occurred when handle initialize event",
e);
}
}
}
private void exportMetadataService() {
if (!isStarting()) {
return;
}
for (DeployListener<ApplicationModel> listener : listeners) {
try {
if (listener instanceof ApplicationDeployListener) {
((ApplicationDeployListener) listener).onModuleStarted(applicationModel);
}
} catch (Throwable e) {
logger.error(
CONFIG_FAILED_START_MODEL,
"",
"",
getIdentifier() + " an exception occurred when handle starting event",
e);
}
}
}
private void onStarting() {
// pending -> starting
// started -> starting
if (!(isPending() || isStarted())) {
return;
}
setStarting();
startFuture = new CompletableFuture();
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " is starting.");
}
}
private void onStarted() {
try {
// starting -> started
if (!isStarting()) {
return;
}
setStarted();
startMetricsCollector();
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " is ready.");
}
// refresh metadata
try {
if (registered) {
ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel);
}
} catch (Exception e) {
logger.error(CONFIG_REFRESH_INSTANCE_ERROR, "", "", "Refresh instance and metadata error.", e);
}
} finally {
// complete future
completeStartFuture(true);
}
}
private void startMetricsCollector() {
DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class);
if (Objects.nonNull(collector) && collector.isThreadpoolCollectEnabled()) {
collector.registryDefaultSample();
}
}
private void completeStartFuture(boolean success) {
if (startFuture != null) {
startFuture.complete(success);
}
}
private void onStopping() {
try {
if (isStopping() || isStopped()) {
return;
}
setStopping();
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " is stopping.");
}
} finally {
completeStartFuture(false);
}
}
private void onStopped() {
try {
if (isStopped()) {
return;
}
setStopped();
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " has stopped.");
}
} finally {
completeStartFuture(false);
}
}
private void onFailed(String msg, Throwable ex) {
try {
setFailed(ex);
logger.error(CONFIG_FAILED_START_MODEL, "", "", msg, ex);
} finally {
completeStartFuture(false);
}
}
private void destroyExecutorRepository() {
// shutdown export/refer executor
executorRepository.shutdownServiceExportExecutor();
executorRepository.shutdownServiceReferExecutor();
ExecutorRepository.getInstance(applicationModel).destroyAll();
}
private void destroyRegistries() {
RegistryManager.getInstance(applicationModel).destroyAll();
}
private void destroyServiceDiscoveries() {
RegistryManager.getInstance(applicationModel).getServiceDiscoveries().forEach(serviceDiscovery -> {
try {
serviceDiscovery.destroy();
} catch (Throwable ignored) {
logger.warn(CONFIG_FAILED_EXECUTE_DESTROY, "", "", ignored.getMessage(), ignored);
}
});
if (logger.isDebugEnabled()) {
logger.debug(getIdentifier() + "'s all ServiceDiscoveries have been destroyed.");
}
}
private void destroyMetadataReports() {
// only destroy MetadataReport of this application
List<MetadataReportFactory> metadataReportFactories =
getExtensionLoader(MetadataReportFactory.class).getLoadedExtensionInstances();
for (MetadataReportFactory metadataReportFactory : metadataReportFactories) {
metadataReportFactory.destroy();
}
}
private ApplicationConfig getApplication() {
return configManager.getApplicationOrElseThrow();
}
}
| 8,605 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.builders.InternalServiceConfigBuilder;
import org.apache.dubbo.metrics.service.MetricsService;
import org.apache.dubbo.metrics.service.MetricsServiceExporter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
/**
* Export metrics service
*/
public class DefaultMetricsServiceExporter implements MetricsServiceExporter, ScopeModelAware {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private ApplicationModel applicationModel;
private MetricsService metricsService;
private volatile ServiceConfig<MetricsService> serviceConfig;
@Override
public void init() {
initialize();
}
private void initialize() {
MetricsConfig metricsConfig =
applicationModel.getApplicationConfigManager().getMetrics().orElse(null);
// TODO compatible with old usage of metrics, remove protocol check after new metrics is ready for use.
if (metricsConfig != null && metricsService == null) {
String protocol = Optional.ofNullable(metricsConfig.getProtocol()).orElse(PROTOCOL_PROMETHEUS);
if (PROTOCOL_PROMETHEUS.equals(protocol)) {
this.metricsService = applicationModel
.getExtensionLoader(MetricsService.class)
.getDefaultExtension();
} else {
logger.warn(
COMMON_METRICS_COLLECTOR_EXCEPTION,
"",
"",
"Protocol " + protocol + " not support for new metrics mechanism. "
+ "Using old metrics mechanism instead.");
}
}
}
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public MetricsServiceExporter export() {
if (metricsService != null) {
if (!isExported()) {
ExecutorService internalServiceExecutor = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getInternalServiceExecutor();
ServiceConfig<MetricsService> serviceConfig = InternalServiceConfigBuilder.<MetricsService>newBuilder(
applicationModel)
.interfaceClass(MetricsService.class)
.protocol(getMetricsConfig().getExportServiceProtocol())
.port(getMetricsConfig().getExportServicePort())
.executor(internalServiceExecutor)
.ref(metricsService)
.registryId("internal-metrics-registry")
.build();
// export
serviceConfig.export();
if (logger.isInfoEnabled()) {
logger.info("The MetricsService exports urls : " + serviceConfig.getExportedUrls());
}
this.serviceConfig = serviceConfig;
} else {
if (logger.isWarnEnabled()) {
logger.warn(
LoggerCodeConstants.INTERNAL_ERROR,
"",
"",
"The MetricsService has been exported : " + serviceConfig.getExportedUrls());
}
}
} else {
if (logger.isInfoEnabled()) {
logger.info("The MetricsConfig not exist, will not export metrics service.");
}
}
return this;
}
@Override
public MetricsServiceExporter unexport() {
if (isExported()) {
serviceConfig.unexport();
}
return this;
}
private MetricsConfig getMetricsConfig() {
Optional<MetricsConfig> metricsConfig =
applicationModel.getApplicationConfigManager().getMetrics();
if (metricsConfig.isPresent()) {
return metricsConfig.get();
} else {
throw new IllegalStateException("There's no MetricsConfig specified.");
}
}
private boolean isExported() {
return serviceConfig != null && serviceConfig.isExported() && !serviceConfig.isUnexported();
}
}
| 8,606 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
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.rpc.Protocol;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelDestroyListener;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_PROTOCOL;
/**
* A cleaner to release resources of framework model
*/
public class FrameworkModelCleaner implements ScopeModelDestroyListener<FrameworkModel> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(FrameworkModelCleaner.class);
private final AtomicBoolean protocolDestroyed = new AtomicBoolean(false);
@Override
public boolean isProtocol() {
return true;
}
@Override
public void onDestroy(FrameworkModel frameworkModel) {
destroyFrameworkResources(frameworkModel);
}
/**
* Destroy all framework resources.
*/
private void destroyFrameworkResources(FrameworkModel frameworkModel) {
// destroy protocol in framework scope
destroyProtocols(frameworkModel);
}
/**
* Destroy all the protocols.
*/
private void destroyProtocols(FrameworkModel frameworkModel) {
if (protocolDestroyed.compareAndSet(false, true)) {
ExtensionLoader<Protocol> loader = frameworkModel.getExtensionLoader(Protocol.class);
for (String protocolName : loader.getLoadedExtensions()) {
try {
Protocol protocol = loader.getLoadedExtension(protocolName);
if (protocol != null) {
protocol.destroy();
}
} catch (Throwable t) {
logger.warn(CONFIG_UNDEFINED_PROTOCOL, "", "", t.getMessage(), t);
}
}
}
}
}
| 8,607 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.constants.RegisterTypeEnum;
import org.apache.dubbo.common.deploy.AbstractDeployer;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployListener;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.common.deploy.ModuleDeployListener;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.utils.SimpleReferenceCache;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_REFERENCE_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_REFER_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_WAIT_EXPORT_REFER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNABLE_DESTROY_MODEL;
/**
* Export/refer services of module
*/
public class DefaultModuleDeployer extends AbstractDeployer<ModuleModel> implements ModuleDeployer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DefaultModuleDeployer.class);
private final List<CompletableFuture<?>> asyncExportingFutures = new ArrayList<>();
private final List<CompletableFuture<?>> asyncReferringFutures = new ArrayList<>();
private final List<ServiceConfigBase<?>> exportedServices = new ArrayList<>();
private final ModuleModel moduleModel;
private final FrameworkExecutorRepository frameworkExecutorRepository;
private final ExecutorRepository executorRepository;
private final ModuleConfigManager configManager;
private final SimpleReferenceCache referenceCache;
private final ApplicationDeployer applicationDeployer;
private CompletableFuture startFuture;
private Boolean background;
private Boolean exportAsync;
private Boolean referAsync;
private CompletableFuture<?> exportFuture;
private CompletableFuture<?> referFuture;
public DefaultModuleDeployer(ModuleModel moduleModel) {
super(moduleModel);
this.moduleModel = moduleModel;
configManager = moduleModel.getConfigManager();
frameworkExecutorRepository = moduleModel
.getApplicationModel()
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class);
executorRepository = ExecutorRepository.getInstance(moduleModel.getApplicationModel());
referenceCache = SimpleReferenceCache.newCache();
applicationDeployer = DefaultApplicationDeployer.get(moduleModel);
// load spi listener
Set<ModuleDeployListener> listeners =
moduleModel.getExtensionLoader(ModuleDeployListener.class).getSupportedExtensionInstances();
for (ModuleDeployListener listener : listeners) {
this.addDeployListener(listener);
}
}
@Override
public void initialize() throws IllegalStateException {
if (initialized) {
return;
}
// Ensure that the initialization is completed when concurrent calls
synchronized (this) {
if (initialized) {
return;
}
onInitialize();
loadConfigs();
// read ModuleConfig
ModuleConfig moduleConfig = moduleModel
.getConfigManager()
.getModule()
.orElseThrow(() -> new IllegalStateException("Default module config is not initialized"));
exportAsync = Boolean.TRUE.equals(moduleConfig.getExportAsync());
referAsync = Boolean.TRUE.equals(moduleConfig.getReferAsync());
// start in background
background = moduleConfig.getBackground();
if (background == null) {
// compatible with old usages
background = isExportBackground() || isReferBackground();
}
initialized = true;
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " has been initialized!");
}
}
}
@Override
public Future start() throws IllegalStateException {
// initialize,maybe deadlock applicationDeployer lock & moduleDeployer lock
applicationDeployer.initialize();
return startSync();
}
private synchronized Future startSync() throws IllegalStateException {
if (isStopping() || isStopped() || isFailed()) {
throw new IllegalStateException(getIdentifier() + " is stopping or stopped, can not start again");
}
try {
if (isStarting() || isStarted()) {
return startFuture;
}
onModuleStarting();
initialize();
// export services
exportServices();
// prepare application instance
// exclude internal module to avoid wait itself
if (moduleModel != moduleModel.getApplicationModel().getInternalModule()) {
applicationDeployer.prepareInternalModule();
}
// refer services
referServices();
// if no async export/refer services, just set started
if (asyncExportingFutures.isEmpty() && asyncReferringFutures.isEmpty()) {
// publish module started event
onModuleStarted();
// register services to registry
registerServices();
// check reference config
checkReferences();
// complete module start future after application state changed
completeStartFuture(true);
} else {
frameworkExecutorRepository.getSharedExecutor().submit(() -> {
try {
// wait for export finish
waitExportFinish();
// wait for refer finish
waitReferFinish();
// publish module started event
onModuleStarted();
// register services to registry
registerServices();
// check reference config
checkReferences();
} catch (Throwable e) {
logger.warn(
CONFIG_FAILED_WAIT_EXPORT_REFER,
"",
"",
"wait for export/refer services occurred an exception",
e);
onModuleFailed(getIdentifier() + " start failed: " + e, e);
} finally {
// complete module start future after application state changed
completeStartFuture(true);
}
});
}
} catch (Throwable e) {
onModuleFailed(getIdentifier() + " start failed: " + e, e);
throw e;
}
return startFuture;
}
@Override
public Future getStartFuture() {
return startFuture;
}
private boolean hasExportedServices() {
return configManager.getServices().size() > 0;
}
@Override
public void stop() throws IllegalStateException {
moduleModel.destroy();
}
@Override
public void preDestroy() throws IllegalStateException {
if (isStopping() || isStopped()) {
return;
}
onModuleStopping();
offline();
}
private void offline() {
try {
ModuleServiceRepository serviceRepository = moduleModel.getServiceRepository();
List<ProviderModel> exportedServices = serviceRepository.getExportedServices();
for (ProviderModel exportedService : exportedServices) {
List<ProviderModel.RegisterStatedURL> statedUrls = exportedService.getStatedUrl();
for (ProviderModel.RegisterStatedURL statedURL : statedUrls) {
if (statedURL.isRegistered()) {
doOffline(statedURL);
}
}
}
} catch (Throwable t) {
logger.error(
LoggerCodeConstants.INTERNAL_ERROR, "", "", "Exceptions occurred when unregister services.", t);
}
}
private void doOffline(ProviderModel.RegisterStatedURL statedURL) {
RegistryFactory registryFactory = statedURL
.getRegistryUrl()
.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryFactory.class)
.getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl());
registry.unregister(statedURL.getProviderUrl());
statedURL.setRegistered(false);
}
@Override
public synchronized void postDestroy() throws IllegalStateException {
if (isStopped()) {
return;
}
unexportServices();
unreferServices();
ModuleServiceRepository serviceRepository = moduleModel.getServiceRepository();
if (serviceRepository != null) {
List<ConsumerModel> consumerModels = serviceRepository.getReferredServices();
for (ConsumerModel consumerModel : consumerModels) {
try {
if (consumerModel.getDestroyRunner() != null) {
consumerModel.getDestroyRunner().run();
}
} catch (Throwable t) {
logger.error(
CONFIG_UNABLE_DESTROY_MODEL,
"there are problems with the custom implementation.",
"",
"Unable to destroy model: consumerModel.",
t);
}
}
List<ProviderModel> exportedServices = serviceRepository.getExportedServices();
for (ProviderModel providerModel : exportedServices) {
try {
if (providerModel.getDestroyRunner() != null) {
providerModel.getDestroyRunner().run();
}
} catch (Throwable t) {
logger.error(
CONFIG_UNABLE_DESTROY_MODEL,
"there are problems with the custom implementation.",
"",
"Unable to destroy model: providerModel.",
t);
}
}
serviceRepository.destroy();
}
onModuleStopped();
}
private void onInitialize() {
for (DeployListener<ModuleModel> listener : listeners) {
try {
listener.onInitialize(moduleModel);
} catch (Throwable e) {
logger.error(
CONFIG_FAILED_START_MODEL,
"",
"",
getIdentifier() + " an exception occurred when handle initialize event",
e);
}
}
}
private void onModuleStarting() {
setStarting();
startFuture = new CompletableFuture();
logger.info(getIdentifier() + " is starting.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STARTING);
}
private void onModuleStarted() {
if (isStarting()) {
setStarted();
logger.info(getIdentifier() + " has started.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STARTED);
}
}
private void onModuleFailed(String msg, Throwable ex) {
try {
try {
// un-export all services if start failure
unexportServices();
} catch (Throwable t) {
logger.info("Failed to un-export services after module failed.", t);
}
setFailed(ex);
logger.error(CONFIG_FAILED_START_MODEL, "", "", "Model start failed: " + msg, ex);
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.FAILED);
} finally {
completeStartFuture(false);
}
}
private void completeStartFuture(boolean value) {
if (startFuture != null && !startFuture.isDone()) {
startFuture.complete(value);
}
if (exportFuture != null && !exportFuture.isDone()) {
exportFuture.cancel(true);
}
if (referFuture != null && !referFuture.isDone()) {
referFuture.cancel(true);
}
}
private void onModuleStopping() {
try {
setStopping();
logger.info(getIdentifier() + " is stopping.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STOPPING);
} finally {
completeStartFuture(false);
}
}
private void onModuleStopped() {
try {
setStopped();
logger.info(getIdentifier() + " has stopped.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STOPPED);
} finally {
completeStartFuture(false);
}
}
private void loadConfigs() {
// load module configs
moduleModel.getConfigManager().loadConfigs();
moduleModel.getConfigManager().refreshAll();
}
private void exportServices() {
for (ServiceConfigBase sc : configManager.getServices()) {
exportServiceInternal(sc);
}
}
private void registerServices() {
for (ServiceConfigBase sc : configManager.getServices()) {
if (!Boolean.FALSE.equals(sc.isRegister())) {
registerServiceInternal(sc);
}
}
applicationDeployer.refreshServiceInstance();
}
private void checkReferences() {
Optional<ModuleConfig> module = configManager.getModule();
long timeout = module.map(ModuleConfig::getCheckReferenceTimeout).orElse(30000L);
for (ReferenceConfigBase<?> rc : configManager.getReferences()) {
referenceCache.check(rc, timeout);
}
}
private void exportServiceInternal(ServiceConfigBase sc) {
ServiceConfig<?> serviceConfig = (ServiceConfig<?>) sc;
if (!serviceConfig.isRefreshed()) {
serviceConfig.refresh();
}
if (sc.isExported()) {
return;
}
if (exportAsync || sc.shouldExportAsync()) {
ExecutorService executor = executorRepository.getServiceExportExecutor();
CompletableFuture<Void> future = CompletableFuture.runAsync(
() -> {
try {
if (!sc.isExported()) {
sc.export();
exportedServices.add(sc);
}
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to async export service config: " + getIdentifier() + " , catch error : "
+ t.getMessage(),
t);
}
},
executor);
asyncExportingFutures.add(future);
} else {
if (!sc.isExported()) {
sc.export(RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER);
exportedServices.add(sc);
}
}
}
private void registerServiceInternal(ServiceConfigBase sc) {
ServiceConfig<?> serviceConfig = (ServiceConfig<?>) sc;
if (!serviceConfig.isRefreshed()) {
serviceConfig.refresh();
}
if (!sc.isExported()) {
return;
}
sc.register(true);
}
private void unexportServices() {
exportedServices.forEach(sc -> {
try {
configManager.removeConfig(sc);
sc.unexport();
} catch (Throwable t) {
logger.info("Failed to un-export service. Service Key: " + sc.getUniqueServiceName(), t);
}
});
exportedServices.clear();
asyncExportingFutures.forEach(future -> {
if (!future.isDone()) {
future.cancel(true);
}
});
asyncExportingFutures.clear();
}
private void referServices() {
configManager.getReferences().forEach(rc -> {
try {
ReferenceConfig<?> referenceConfig = (ReferenceConfig<?>) rc;
if (!referenceConfig.isRefreshed()) {
referenceConfig.refresh();
}
if (rc.shouldInit()) {
if (referAsync || rc.shouldReferAsync()) {
ExecutorService executor = executorRepository.getServiceReferExecutor();
CompletableFuture<Void> future = CompletableFuture.runAsync(
() -> {
try {
referenceCache.get(rc, false);
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to async export service config: " + getIdentifier()
+ " , catch error : " + t.getMessage(),
t);
}
},
executor);
asyncReferringFutures.add(future);
} else {
referenceCache.get(rc, false);
}
}
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_REFERENCE_MODEL,
"",
"",
"Model reference failed: " + getIdentifier() + " , catch error : " + t.getMessage(),
t);
referenceCache.destroy(rc);
throw t;
}
});
}
private void unreferServices() {
try {
asyncReferringFutures.forEach(future -> {
if (!future.isDone()) {
future.cancel(true);
}
});
asyncReferringFutures.clear();
referenceCache.destroyAll();
for (ReferenceConfigBase<?> rc : configManager.getReferences()) {
rc.destroy();
}
} catch (Exception ignored) {
}
}
private void waitExportFinish() {
try {
logger.info(getIdentifier() + " waiting services exporting ...");
exportFuture = CompletableFuture.allOf(asyncExportingFutures.toArray(new CompletableFuture[0]));
exportFuture.get();
} catch (Throwable e) {
logger.warn(
CONFIG_FAILED_EXPORT_SERVICE,
"",
"",
getIdentifier() + " export services occurred an exception: " + e.toString());
} finally {
logger.info(getIdentifier() + " export services finished.");
asyncExportingFutures.clear();
}
}
private void waitReferFinish() {
try {
logger.info(getIdentifier() + " waiting services referring ...");
referFuture = CompletableFuture.allOf(asyncReferringFutures.toArray(new CompletableFuture[0]));
referFuture.get();
} catch (Throwable e) {
logger.warn(
CONFIG_FAILED_REFER_SERVICE,
"",
"",
getIdentifier() + " refer services occurred an exception: " + e.toString());
} finally {
logger.info(getIdentifier() + " refer services finished.");
asyncReferringFutures.clear();
}
}
@Override
public boolean isBackground() {
return background;
}
private boolean isExportBackground() {
return moduleModel.getConfigManager().getProviders().stream()
.map(ProviderConfig::getExportBackground)
.anyMatch(k -> k != null && k);
}
private boolean isReferBackground() {
return moduleModel.getConfigManager().getConsumers().stream()
.map(ConsumerConfig::getReferBackground)
.anyMatch(k -> k != null && k);
}
@Override
public ReferenceCache getReferenceCache() {
return referenceCache;
}
/**
* Prepare for export/refer service, trigger initializing application and module
*/
@Override
public void prepare() {
applicationDeployer.initialize();
this.initialize();
}
}
| 8,608 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.List;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_WRONG_USE;
/**
* A impl of ReferenceCache for Application
*/
public class CompositeReferenceCache implements ReferenceCache {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(CompositeReferenceCache.class);
private final ApplicationModel applicationModel;
public CompositeReferenceCache(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public <T> T get(ReferenceConfigBase<T> referenceConfig, boolean check) {
Class<?> type = referenceConfig.getInterfaceClass();
String key = BaseServiceMetadata.buildServiceKey(
type.getName(), referenceConfig.getGroup(), referenceConfig.getVersion());
boolean singleton = referenceConfig.getSingleton() == null || referenceConfig.getSingleton();
T proxy = null;
if (singleton) {
proxy = get(key, (Class<T>) type);
} else {
logger.warn(
CONFIG_API_WRONG_USE,
"the api method is being used incorrectly",
"",
"Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. "
+ "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)");
}
if (proxy == null) {
proxy = referenceConfig.get(check);
}
return proxy;
}
@Override
public <T> T get(String key, Class<T> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
T proxy = moduleModel.getDeployer().getReferenceCache().get(key, type);
if (proxy != null) {
return proxy;
}
}
return null;
}
@Override
public <T> T get(String key) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
T proxy = moduleModel.getDeployer().getReferenceCache().get(key);
if (proxy != null) {
return proxy;
}
}
return null;
}
@Override
public <T> List<T> getAll(Class<T> type) {
List<T> proxies = new ArrayList<>();
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
proxies.addAll(moduleModel.getDeployer().getReferenceCache().getAll(type));
}
return proxies;
}
@Override
public <T> T get(Class<T> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
T proxy = moduleModel.getDeployer().getReferenceCache().get(type);
if (proxy != null) {
return proxy;
}
}
return null;
}
@Override
public void destroy(String key, Class<?> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().destroy(key, type);
}
}
@Override
public void check(String key, Class<?> type, long timeout) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().check(key, type, timeout);
}
}
@Override
public <T> void check(ReferenceConfigBase<T> referenceConfig, long timeout) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().check(referenceConfig, timeout);
}
}
@Override
public void destroy(Class<?> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().destroy(type);
}
}
@Override
public <T> void destroy(ReferenceConfigBase<T> referenceConfig) {
referenceConfig.getScopeModel().getDeployer().getReferenceCache().destroy(referenceConfig);
}
@Override
public void destroyAll() {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().destroyAll();
}
}
}
| 8,609 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_WRONG_USE;
/**
* A simple util class for cache {@link ReferenceConfigBase}.
* <p>
* {@link ReferenceConfigBase} is a heavy Object, it's necessary to cache these object
* for the framework which create {@link ReferenceConfigBase} frequently.
* <p>
* You can implement and use your own {@link ReferenceConfigBase} cache if you need use complicate strategy.
*/
public class SimpleReferenceCache implements ReferenceCache {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(SimpleReferenceCache.class);
public static final String DEFAULT_NAME = "_DEFAULT_";
/**
* Create the key with the <b>Group</b>, <b>Interface</b> and <b>version</b> attribute of {@link ReferenceConfigBase}.
* <p>
* key example: <code>group1/org.apache.dubbo.foo.FooService:1.0.0</code>.
*/
public static final KeyGenerator DEFAULT_KEY_GENERATOR = referenceConfig -> {
String iName = referenceConfig.getInterface();
if (StringUtils.isBlank(iName)) {
Class<?> clazz = referenceConfig.getInterfaceClass();
iName = clazz.getName();
}
if (StringUtils.isBlank(iName)) {
throw new IllegalArgumentException("No interface info in ReferenceConfig" + referenceConfig);
}
return BaseServiceMetadata.buildServiceKey(iName, referenceConfig.getGroup(), referenceConfig.getVersion());
};
private static final AtomicInteger nameIndex = new AtomicInteger();
static final ConcurrentMap<String, SimpleReferenceCache> CACHE_HOLDER = new ConcurrentHashMap<>();
private final String name;
private final KeyGenerator generator;
private final ConcurrentMap<String, List<ReferenceConfigBase<?>>> referenceKeyMap = new ConcurrentHashMap<>();
private final ConcurrentMap<Class<?>, List<ReferenceConfigBase<?>>> referenceTypeMap = new ConcurrentHashMap<>();
private final Map<ReferenceConfigBase<?>, Object> references = new ConcurrentHashMap<>();
protected SimpleReferenceCache(String name, KeyGenerator generator) {
this.name = name;
this.generator = generator;
}
/**
* Get the cache use default name and {@link #DEFAULT_KEY_GENERATOR} to generate cache key.
* Create cache if not existed yet.
*/
public static SimpleReferenceCache getCache() {
return getCache(DEFAULT_NAME);
}
public static SimpleReferenceCache newCache() {
return getCache(DEFAULT_NAME + "#" + nameIndex.incrementAndGet());
}
/**
* Get the cache use specified name and {@link KeyGenerator}.
* Create cache if not existed yet.
*/
public static SimpleReferenceCache getCache(String name) {
return getCache(name, DEFAULT_KEY_GENERATOR);
}
/**
* Get the cache use specified {@link KeyGenerator}.
* Create cache if not existed yet.
*/
public static SimpleReferenceCache getCache(String name, KeyGenerator keyGenerator) {
return ConcurrentHashMapUtils.computeIfAbsent(
CACHE_HOLDER, name, k -> new SimpleReferenceCache(k, keyGenerator));
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(ReferenceConfigBase<T> rc, boolean check) {
String key = generator.generateKey(rc);
Class<?> type = rc.getInterfaceClass();
boolean singleton = rc.getSingleton() == null || rc.getSingleton();
T proxy = null;
// Check existing proxy of the same 'key' and 'type' first.
if (singleton) {
proxy = get(key, (Class<T>) type);
} else {
logger.warn(
CONFIG_API_WRONG_USE,
"",
"",
"Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. "
+ "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)");
}
if (proxy == null) {
List<ReferenceConfigBase<?>> referencesOfType = ConcurrentHashMapUtils.computeIfAbsent(
referenceTypeMap, type, _t -> Collections.synchronizedList(new ArrayList<>()));
referencesOfType.add(rc);
List<ReferenceConfigBase<?>> referenceConfigList = ConcurrentHashMapUtils.computeIfAbsent(
referenceKeyMap, key, _k -> Collections.synchronizedList(new ArrayList<>()));
referenceConfigList.add(rc);
proxy = rc.get(check);
}
return proxy;
}
/**
* Fetch cache with the specified key. The key is decided by KeyGenerator passed-in. If the default KeyGenerator is
* used, then the key is in the format of <code>group/interfaceClass:version</code>
*
* @param key cache key
* @param type object class
* @param <T> object type
* @return object from the cached ReferenceConfigBase
* @see KeyGenerator#generateKey(ReferenceConfigBase)
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> type) {
List<ReferenceConfigBase<?>> referenceConfigs = referenceKeyMap.get(key);
if (CollectionUtils.isNotEmpty(referenceConfigs)) {
return (T) referenceConfigs.get(0).get();
}
return null;
}
/**
* Check and return existing ReferenceConfig and its corresponding proxy instance.
*
* @param key ServiceKey
* @param <T> service interface type
* @return the existing proxy instance of the same service key
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(String key) {
List<ReferenceConfigBase<?>> referenceConfigBases = referenceKeyMap.get(key);
if (CollectionUtils.isNotEmpty(referenceConfigBases)) {
return (T) referenceConfigBases.get(0).get();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> type) {
List<ReferenceConfigBase<?>> referenceConfigBases = referenceTypeMap.get(type);
if (CollectionUtils.isEmpty(referenceConfigBases)) {
return Collections.EMPTY_LIST;
}
List proxiesOfType = new ArrayList(referenceConfigBases.size());
for (ReferenceConfigBase<?> rc : referenceConfigBases) {
proxiesOfType.add(rc.get());
}
return Collections.unmodifiableList(proxiesOfType);
}
/**
* Check and return existing ReferenceConfig and its corresponding proxy instance.
*
* @param type service interface class
* @param <T> service interface type
* @return the existing proxy instance of the same interface definition
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(Class<T> type) {
List<ReferenceConfigBase<?>> referenceConfigBases = referenceTypeMap.get(type);
if (CollectionUtils.isNotEmpty(referenceConfigBases)) {
return (T) referenceConfigBases.get(0).get();
}
return null;
}
@Override
public void check(String key, Class<?> type, long timeout) {
List<ReferenceConfigBase<?>> referencesOfKey = referenceKeyMap.get(key);
if (CollectionUtils.isEmpty(referencesOfKey)) {
return;
}
List<ReferenceConfigBase<?>> referencesOfType = referenceTypeMap.get(type);
if (CollectionUtils.isEmpty(referencesOfType)) {
return;
}
for (ReferenceConfigBase<?> rc : referencesOfKey) {
rc.checkOrDestroy(timeout);
}
}
@Override
public <T> void check(ReferenceConfigBase<T> referenceConfig, long timeout) {
String key = generator.generateKey(referenceConfig);
Class<?> type = referenceConfig.getInterfaceClass();
check(key, type, timeout);
}
@Override
public void destroy(String key, Class<?> type) {
List<ReferenceConfigBase<?>> referencesOfKey = referenceKeyMap.remove(key);
if (CollectionUtils.isEmpty(referencesOfKey)) {
return;
}
List<ReferenceConfigBase<?>> referencesOfType = referenceTypeMap.get(type);
if (CollectionUtils.isEmpty(referencesOfType)) {
return;
}
for (ReferenceConfigBase<?> rc : referencesOfKey) {
referencesOfType.remove(rc);
destroyReference(rc);
}
}
@Override
public void destroy(Class<?> type) {
List<ReferenceConfigBase<?>> referencesOfType = referenceTypeMap.remove(type);
for (ReferenceConfigBase<?> rc : referencesOfType) {
String key = generator.generateKey(rc);
referenceKeyMap.remove(key);
destroyReference(rc);
}
}
/**
* clear and destroy one {@link ReferenceConfigBase} in the cache.
*
* @param referenceConfig use for create key.
*/
@Override
public <T> void destroy(ReferenceConfigBase<T> referenceConfig) {
String key = generator.generateKey(referenceConfig);
Class<?> type = referenceConfig.getInterfaceClass();
destroy(key, type);
}
/**
* clear and destroy all {@link ReferenceConfigBase} in the cache.
*/
@Override
public void destroyAll() {
if (CollectionUtils.isEmptyMap(referenceKeyMap)) {
return;
}
referenceKeyMap.forEach((_k, referencesOfKey) -> {
for (ReferenceConfigBase<?> rc : referencesOfKey) {
destroyReference(rc);
}
});
referenceKeyMap.clear();
referenceTypeMap.clear();
}
private void destroyReference(ReferenceConfigBase<?> rc) {
Destroyable proxy = (Destroyable) rc.get();
if (proxy != null) {
proxy.$destroy();
}
rc.destroy();
}
public Map<String, List<ReferenceConfigBase<?>>> getReferenceMap() {
return referenceKeyMap;
}
public Map<Class<?>, List<ReferenceConfigBase<?>>> getReferenceTypeMap() {
return referenceTypeMap;
}
@Override
public String toString() {
return "ReferenceCache(name: " + name + ")";
}
public interface KeyGenerator {
String generateKey(ReferenceConfigBase<?> referenceConfig);
}
}
| 8,610 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.PropertiesConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.AbstractInterfaceConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.monitor.MonitorFactory;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.Dispatcher;
import org.apache.dubbo.remoting.Transporter;
import org.apache.dubbo.remoting.exchange.Exchanger;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.support.MockInvoker;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_MONITOR_ADDRESS;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.FILTER_KEY;
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.LOADBALANCE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
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.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_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.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_ALL;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INSTANCE;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INTERFACE;
import static org.apache.dubbo.common.constants.RegistryConstants.DUBBO_REGISTER_MODE_DEFAULT_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
import static org.apache.dubbo.config.Constants.ARCHITECTURE;
import static org.apache.dubbo.config.Constants.CONTEXTPATH_KEY;
import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY;
import static org.apache.dubbo.config.Constants.ENVIRONMENT;
import static org.apache.dubbo.config.Constants.IGNORE_CHECK_KEYS;
import static org.apache.dubbo.config.Constants.LAYER_KEY;
import static org.apache.dubbo.config.Constants.NAME;
import static org.apache.dubbo.config.Constants.ORGANIZATION;
import static org.apache.dubbo.config.Constants.OWNER;
import static org.apache.dubbo.config.Constants.STATUS_KEY;
import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.registry.Constants.SUBSCRIBE_KEY;
import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
import static org.apache.dubbo.remoting.Constants.CODEC_KEY;
import static org.apache.dubbo.remoting.Constants.DISPATCHER_KEY;
import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY;
import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
import static org.apache.dubbo.remoting.Constants.SERVER_KEY;
import static org.apache.dubbo.remoting.Constants.TELNET_KEY;
import static org.apache.dubbo.remoting.Constants.TRANSPORTER_KEY;
import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX;
import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX;
import static org.apache.dubbo.rpc.Constants.LOCAL_KEY;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX;
import static org.apache.dubbo.rpc.Constants.THROW_PREFIX;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
public class ConfigValidationUtils {
private static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigValidationUtils.class);
/**
* The maximum length of a <b>parameter's value</b>
*/
private static final int MAX_LENGTH = 200;
/**
* The maximum length of a <b>path</b>
*/
private static final int MAX_PATH_LENGTH = 200;
/**
* The rule qualification for <b>name</b>
*/
private static final Pattern PATTERN_NAME = Pattern.compile("[\\-._0-9a-zA-Z]+");
/**
* The rule qualification for <b>multiply name</b>
*/
private static final Pattern PATTERN_MULTI_NAME = Pattern.compile("[,\\-._0-9a-zA-Z]+");
/**
* The rule qualification for <b>method names</b>
*/
private static final Pattern PATTERN_METHOD_NAME = Pattern.compile("[a-zA-Z][0-9a-zA-Z]*");
/**
* The rule qualification for <b>path</b>
*/
private static final Pattern PATTERN_PATH = Pattern.compile("[/\\-$._0-9a-zA-Z]+");
/**
* The pattern matches a value who has a symbol
*/
private static final Pattern PATTERN_NAME_HAS_SYMBOL = Pattern.compile("[:*,\\s/\\-._0-9a-zA-Z]+");
/**
* The pattern matches a property key
*/
private static final Pattern PATTERN_KEY = Pattern.compile("[*,\\-._0-9a-zA-Z]+");
public static final String IPV6_START_MARK = "[";
public static final String IPV6_END_MARK = "]";
public static List<URL> loadRegistries(AbstractInterfaceConfig interfaceConfig, boolean provider) {
// check && override if necessary
List<URL> registryList = new ArrayList<>();
ApplicationConfig application = interfaceConfig.getApplication();
List<RegistryConfig> registries = interfaceConfig.getRegistries();
if (CollectionUtils.isNotEmpty(registries)) {
for (RegistryConfig config : registries) {
// try to refresh registry in case it is set directly by user using config.setRegistries()
if (!config.isRefreshed()) {
config.refresh();
}
String address = config.getAddress();
if (StringUtils.isEmpty(address)) {
address = ANYHOST_VALUE;
}
if (!RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) {
Map<String, String> map = new HashMap<String, String>();
AbstractConfig.appendParameters(map, application);
AbstractConfig.appendParameters(map, config);
map.put(PATH_KEY, RegistryService.class.getName());
AbstractInterfaceConfig.appendRuntimeParameters(map);
if (!map.containsKey(PROTOCOL_KEY)) {
map.put(PROTOCOL_KEY, DUBBO_PROTOCOL);
}
List<URL> urls = UrlUtils.parseURLs(address, map);
for (URL url : urls) {
url = URLBuilder.from(url)
.addParameter(REGISTRY_KEY, url.getProtocol())
.setProtocol(extractRegistryType(url))
.setScopeModel(interfaceConfig.getScopeModel())
.build();
// provider delay register state will be checked in RegistryProtocol#export
if (provider || url.getParameter(SUBSCRIBE_KEY, true)) {
registryList.add(url);
}
}
}
}
}
return genCompatibleRegistries(interfaceConfig.getScopeModel(), registryList, provider);
}
private static List<URL> genCompatibleRegistries(ScopeModel scopeModel, List<URL> registryList, boolean provider) {
List<URL> result = new ArrayList<>(registryList.size());
registryList.forEach(registryURL -> {
if (provider) {
// for registries enabled service discovery, automatically register interface compatible addresses.
String registerMode;
if (SERVICE_REGISTRY_PROTOCOL.equals(registryURL.getProtocol())) {
registerMode = registryURL.getParameter(
REGISTER_MODE_KEY,
ConfigurationUtils.getCachedDynamicProperty(
scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_INSTANCE));
if (!isValidRegisterMode(registerMode)) {
registerMode = DEFAULT_REGISTER_MODE_INSTANCE;
}
result.add(registryURL);
if (DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)
&& registryNotExists(registryURL, registryList, REGISTRY_PROTOCOL)) {
URL interfaceCompatibleRegistryURL = URLBuilder.from(registryURL)
.setProtocol(REGISTRY_PROTOCOL)
.removeParameter(REGISTRY_TYPE_KEY)
.build();
result.add(interfaceCompatibleRegistryURL);
}
} else {
registerMode = registryURL.getParameter(
REGISTER_MODE_KEY,
ConfigurationUtils.getCachedDynamicProperty(
scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_ALL));
if (!isValidRegisterMode(registerMode)) {
registerMode = DEFAULT_REGISTER_MODE_INTERFACE;
}
if ((DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(registerMode)
|| DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode))
&& registryNotExists(registryURL, registryList, SERVICE_REGISTRY_PROTOCOL)) {
URL serviceDiscoveryRegistryURL = URLBuilder.from(registryURL)
.setProtocol(SERVICE_REGISTRY_PROTOCOL)
.removeParameter(REGISTRY_TYPE_KEY)
.build();
result.add(serviceDiscoveryRegistryURL);
}
if (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(registerMode)
|| DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)) {
result.add(registryURL);
}
}
FrameworkStatusReportService reportService = ScopeModelUtil.getApplicationModel(scopeModel)
.getBeanFactory()
.getBean(FrameworkStatusReportService.class);
reportService.reportRegistrationStatus(reportService.createRegistrationReport(registerMode));
} else {
result.add(registryURL);
}
});
return result;
}
private static boolean isValidRegisterMode(String mode) {
return isNotEmpty(mode)
&& (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(mode)
|| DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(mode)
|| DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(mode));
}
private static boolean registryNotExists(URL registryURL, List<URL> registryList, String registryType) {
return registryList.stream()
.noneMatch(url -> registryType.equals(url.getProtocol())
&& registryURL.getBackupAddress().equals(url.getBackupAddress()));
}
public static URL loadMonitor(AbstractInterfaceConfig interfaceConfig, URL registryURL) {
Map<String, String> map = new HashMap<String, String>();
map.put(INTERFACE_KEY, MonitorService.class.getName());
AbstractInterfaceConfig.appendRuntimeParameters(map);
// set ip
String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
if (StringUtils.isEmpty(hostToRegistry)) {
hostToRegistry = NetUtils.getLocalHost();
} else if (NetUtils.isInvalidLocalHost(hostToRegistry)) {
throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY
+ ", value:" + hostToRegistry);
}
map.put(REGISTER_IP_KEY, hostToRegistry);
MonitorConfig monitor = interfaceConfig.getMonitor();
ApplicationConfig application = interfaceConfig.getApplication();
AbstractConfig.appendParameters(map, monitor);
AbstractConfig.appendParameters(map, application);
String address = null;
String sysAddress = System.getProperty(DUBBO_MONITOR_ADDRESS);
if (sysAddress != null && sysAddress.length() > 0) {
address = sysAddress;
} else if (monitor != null) {
address = monitor.getAddress();
}
String protocol = monitor == null ? null : monitor.getProtocol();
if (monitor != null
&& (REGISTRY_PROTOCOL.equals(protocol) || SERVICE_REGISTRY_PROTOCOL.equals(protocol))
&& registryURL != null) {
return URLBuilder.from(registryURL)
.setProtocol(DUBBO_PROTOCOL)
.addParameter(PROTOCOL_KEY, protocol)
.putAttribute(REFER_KEY, map)
.build();
} else if (ConfigUtils.isNotEmpty(address) || ConfigUtils.isNotEmpty(protocol)) {
if (!map.containsKey(PROTOCOL_KEY)) {
if (interfaceConfig
.getScopeModel()
.getExtensionLoader(MonitorFactory.class)
.hasExtension(LOGSTAT_PROTOCOL)) {
map.put(PROTOCOL_KEY, LOGSTAT_PROTOCOL);
} else if (ConfigUtils.isNotEmpty(protocol)) {
map.put(PROTOCOL_KEY, protocol);
} else {
map.put(PROTOCOL_KEY, DUBBO_PROTOCOL);
}
}
if (ConfigUtils.isEmpty(address)) {
address = LOCALHOST_VALUE;
}
return UrlUtils.parseURL(address, map);
}
return null;
}
/**
* Legitimacy check and setup of local simulated operations. The operations can be a string with Simple operation or
* a classname whose {@link Class} implements a particular function
*
* @param interfaceClass for provider side, it is the {@link Class} of the service that will be exported; for consumer
* side, it is the {@link Class} of the remote service interface that will be referenced
*/
public static void checkMock(Class<?> interfaceClass, AbstractInterfaceConfig config) {
String mock = config.getMock();
if (ConfigUtils.isEmpty(mock)) {
return;
}
String normalizedMock = MockInvoker.normalizeMock(mock);
if (normalizedMock.startsWith(RETURN_PREFIX)) {
normalizedMock = normalizedMock.substring(RETURN_PREFIX.length()).trim();
try {
// Check whether the mock value is legal, if it is illegal, throw exception
MockInvoker.parseMockValue(normalizedMock);
} catch (Exception e) {
throw new IllegalStateException(
"Illegal mock return in <dubbo:service/reference ... " + "mock=\"" + mock + "\" />");
}
} else if (normalizedMock.startsWith(THROW_PREFIX)) {
normalizedMock = normalizedMock.substring(THROW_PREFIX.length()).trim();
if (ConfigUtils.isNotEmpty(normalizedMock)) {
try {
// Check whether the mock value is legal
MockInvoker.getThrowable(normalizedMock);
} catch (Exception e) {
throw new IllegalStateException(
"Illegal mock throw in <dubbo:service/reference ... " + "mock=\"" + mock + "\" />");
}
}
} else {
// Check whether the mock class is a implementation of the interfaceClass, and if it has a default
// constructor
MockInvoker.getMockObject(config.getScopeModel().getExtensionDirector(), normalizedMock, interfaceClass);
}
}
public static void validateAbstractInterfaceConfig(AbstractInterfaceConfig config) {
checkName(LOCAL_KEY, config.getLocal());
checkName("stub", config.getStub());
checkMultiName("owner", config.getOwner());
checkExtension(config.getScopeModel(), ProxyFactory.class, PROXY_KEY, config.getProxy());
checkExtension(config.getScopeModel(), Cluster.class, CLUSTER_KEY, config.getCluster());
checkMultiExtension(
config.getScopeModel(),
Arrays.asList(Filter.class, ClusterFilter.class),
FILTER_KEY,
config.getFilter());
checkNameHasSymbol(LAYER_KEY, config.getLayer());
List<MethodConfig> methods = config.getMethods();
if (CollectionUtils.isNotEmpty(methods)) {
methods.forEach(ConfigValidationUtils::validateMethodConfig);
}
}
public static void validateServiceConfig(ServiceConfig config) {
checkKey(VERSION_KEY, config.getVersion());
checkKey(GROUP_KEY, config.getGroup());
checkName(TOKEN_KEY, config.getToken());
checkPathName(PATH_KEY, config.getPath());
checkMultiExtension(config.getScopeModel(), ExporterListener.class, "listener", config.getListener());
validateAbstractInterfaceConfig(config);
List<RegistryConfig> registries = config.getRegistries();
if (registries != null) {
for (RegistryConfig registry : registries) {
validateRegistryConfig(registry);
}
}
List<ProtocolConfig> protocols = config.getProtocols();
if (protocols != null) {
for (ProtocolConfig protocol : protocols) {
validateProtocolConfig(protocol);
}
}
ProviderConfig providerConfig = config.getProvider();
if (providerConfig != null) {
validateProviderConfig(providerConfig);
}
}
public static void validateReferenceConfig(ReferenceConfig config) {
checkMultiExtension(config.getScopeModel(), InvokerListener.class, "listener", config.getListener());
checkKey(VERSION_KEY, config.getVersion());
checkKey(GROUP_KEY, config.getGroup());
checkName(CLIENT_KEY, config.getClient());
validateAbstractInterfaceConfig(config);
List<RegistryConfig> registries = config.getRegistries();
if (registries != null) {
for (RegistryConfig registry : registries) {
validateRegistryConfig(registry);
}
}
ConsumerConfig consumerConfig = config.getConsumer();
if (consumerConfig != null) {
validateConsumerConfig(consumerConfig);
}
}
public static void validateConfigCenterConfig(ConfigCenterConfig config) {
if (config != null) {
checkParameterName(config.getParameters());
}
}
public static void validateApplicationConfig(ApplicationConfig config) {
if (config == null) {
return;
}
if (!config.isValid()) {
throw new IllegalStateException("No application config found or it's not a valid config! "
+ "Please add <dubbo:application name=\"...\" /> to your spring config.");
}
// backward compatibility
ScopeModel scopeModel = ScopeModelUtil.getOrDefaultApplicationModel(config.getScopeModel());
PropertiesConfiguration configuration = scopeModel.modelEnvironment().getPropertiesConfiguration();
String wait = configuration.getProperty(SHUTDOWN_WAIT_KEY);
if (wait != null && wait.trim().length() > 0) {
System.setProperty(SHUTDOWN_WAIT_KEY, wait.trim());
} else {
wait = configuration.getProperty(SHUTDOWN_WAIT_SECONDS_KEY);
if (wait != null && wait.trim().length() > 0) {
System.setProperty(SHUTDOWN_WAIT_SECONDS_KEY, wait.trim());
}
}
checkName(NAME, config.getName());
checkMultiName(OWNER, config.getOwner());
checkName(ORGANIZATION, config.getOrganization());
checkName(ARCHITECTURE, config.getArchitecture());
checkName(ENVIRONMENT, config.getEnvironment());
checkParameterName(config.getParameters());
checkQosDependency(config);
}
private static void checkQosDependency(ApplicationConfig config) {
if (!Boolean.FALSE.equals(config.getQosEnable())) {
try {
ClassUtils.forName("org.apache.dubbo.qos.protocol.QosProtocolWrapper");
} catch (ClassNotFoundException e) {
logger.warn(
COMMON_CLASS_NOT_FOUND,
"",
"",
"No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly.",
e);
}
}
}
public static void validateModuleConfig(ModuleConfig config) {
if (config != null) {
checkName(NAME, config.getName());
checkName(OWNER, config.getOwner());
checkName(ORGANIZATION, config.getOrganization());
}
}
public static boolean isValidMetadataConfig(MetadataReportConfig metadataReportConfig) {
if (metadataReportConfig == null) {
return false;
}
if (Boolean.FALSE.equals(metadataReportConfig.getReportMetadata())
&& Boolean.FALSE.equals(metadataReportConfig.getReportDefinition())) {
return false;
}
return !isEmpty(metadataReportConfig.getAddress());
}
public static void validateMetadataConfig(MetadataReportConfig metadataReportConfig) {
if (!isValidMetadataConfig(metadataReportConfig)) {
return;
}
String address = metadataReportConfig.getAddress();
String protocol = metadataReportConfig.getProtocol();
if ((isEmpty(address) || !address.contains("://")) && isEmpty(protocol)) {
throw new IllegalArgumentException(
"Please specify valid protocol or address for metadata report " + address);
}
}
public static void validateMetricsConfig(MetricsConfig metricsConfig) {
if (metricsConfig == null) {
return;
}
}
public static void validateTracingConfig(TracingConfig tracingConfig) {
if (tracingConfig == null) {
return;
}
}
public static void validateSslConfig(SslConfig sslConfig) {
if (sslConfig == null) {
return;
}
}
public static void validateMonitorConfig(MonitorConfig config) {
if (config != null) {
if (!config.isValid()) {
logger.info("There's no valid monitor config found, if you want to open monitor statistics for Dubbo, "
+ "please make sure your monitor is configured properly.");
}
checkParameterName(config.getParameters());
}
}
public static void validateProtocolConfig(ProtocolConfig config) {
if (config != null) {
String name = config.getName();
checkName("name", name);
checkHost(HOST_KEY, config.getHost());
checkPathName("contextpath", config.getContextpath());
if (DUBBO_PROTOCOL.equals(name)) {
checkMultiExtension(config.getScopeModel(), Codec2.class, CODEC_KEY, config.getCodec());
checkMultiExtension(
config.getScopeModel(), Serialization.class, SERIALIZATION_KEY, config.getSerialization());
checkMultiExtension(config.getScopeModel(), Transporter.class, SERVER_KEY, config.getServer());
checkMultiExtension(config.getScopeModel(), Transporter.class, CLIENT_KEY, config.getClient());
}
checkMultiExtension(config.getScopeModel(), TelnetHandler.class, TELNET_KEY, config.getTelnet());
checkMultiExtension(config.getScopeModel(), StatusChecker.class, "status", config.getStatus());
checkExtension(config.getScopeModel(), Transporter.class, TRANSPORTER_KEY, config.getTransporter());
checkExtension(config.getScopeModel(), Exchanger.class, EXCHANGER_KEY, config.getExchanger());
checkExtension(config.getScopeModel(), Dispatcher.class, DISPATCHER_KEY, config.getDispatcher());
checkExtension(config.getScopeModel(), Dispatcher.class, "dispather", config.getDispather());
checkExtension(config.getScopeModel(), ThreadPool.class, THREADPOOL_KEY, config.getThreadpool());
}
}
public static void validateProviderConfig(ProviderConfig config) {
checkPathName(CONTEXTPATH_KEY, config.getContextpath());
checkExtension(config.getScopeModel(), ThreadPool.class, THREADPOOL_KEY, config.getThreadpool());
checkMultiExtension(config.getScopeModel(), TelnetHandler.class, TELNET_KEY, config.getTelnet());
checkMultiExtension(config.getScopeModel(), StatusChecker.class, STATUS_KEY, config.getStatus());
checkExtension(config.getScopeModel(), Transporter.class, TRANSPORTER_KEY, config.getTransporter());
checkExtension(config.getScopeModel(), Exchanger.class, EXCHANGER_KEY, config.getExchanger());
}
public static void validateConsumerConfig(ConsumerConfig config) {
if (config == null) {
return;
}
}
public static void validateRegistryConfig(RegistryConfig config) {
checkName(PROTOCOL_KEY, config.getProtocol());
checkName(USERNAME_KEY, config.getUsername());
checkLength(PASSWORD_KEY, config.getPassword());
checkPathLength(FILE_KEY, config.getFile());
checkName(TRANSPORTER_KEY, config.getTransporter());
checkName(SERVER_KEY, config.getServer());
checkName(CLIENT_KEY, config.getClient());
checkParameterName(config.getParameters());
}
public static void validateMethodConfig(MethodConfig config) {
checkExtension(config.getScopeModel(), LoadBalance.class, LOADBALANCE_KEY, config.getLoadbalance());
checkParameterName(config.getParameters());
checkMethodName("name", config.getName());
String mock = config.getMock();
if (isNotEmpty(mock)) {
if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX + " ")) {
checkLength(MOCK_KEY, mock);
} else if (mock.startsWith(FAIL_PREFIX) || mock.startsWith(FORCE_PREFIX)) {
checkNameHasSymbol(MOCK_KEY, mock);
} else {
checkName(MOCK_KEY, mock);
}
}
}
private static String extractRegistryType(URL url) {
return UrlUtils.hasServiceDiscoveryRegistryTypeKey(url)
? SERVICE_REGISTRY_PROTOCOL
: getRegistryProtocolType(url);
}
private static String getRegistryProtocolType(URL url) {
String registryProtocol = url.getParameter("registry-protocol-type");
return isNotEmpty(registryProtocol) ? registryProtocol : REGISTRY_PROTOCOL;
}
public static void checkExtension(ScopeModel scopeModel, Class<?> type, String property, String value) {
checkName(property, value);
if (isNotEmpty(value) && !scopeModel.getExtensionLoader(type).hasExtension(value)) {
throw new IllegalStateException("No such extension " + value + " for " + property + "/" + type.getName());
}
}
/**
* Check whether there is a <code>Extension</code> who's name (property) is <code>value</code> (special treatment is
* required)
*
* @param type The Extension type
* @param property The extension key
* @param value The Extension name
*/
public static void checkMultiExtension(ScopeModel scopeModel, Class<?> type, String property, String value) {
checkMultiExtension(scopeModel, Collections.singletonList(type), property, value);
}
public static void checkMultiExtension(ScopeModel scopeModel, List<Class<?>> types, String property, String value) {
checkMultiName(property, value);
if (isNotEmpty(value)) {
String[] values = value.split("\\s*[,]+\\s*");
for (String v : values) {
v = StringUtils.trim(v);
if (v.startsWith(REMOVE_VALUE_PREFIX)) {
continue;
}
if (DEFAULT_KEY.equals(v)) {
continue;
}
boolean match = false;
for (Class<?> type : types) {
if (scopeModel.getExtensionLoader(type).hasExtension(v)) {
match = true;
}
}
if (!match) {
throw new IllegalStateException("No such extension " + v + " for " + property + "/"
+ types.stream().map(Class::getName).collect(Collectors.joining(",")));
}
}
}
}
public static void checkLength(String property, String value) {
checkProperty(property, value, MAX_LENGTH, null);
}
public static void checkPathLength(String property, String value) {
checkProperty(property, value, MAX_PATH_LENGTH, null);
}
public static void checkName(String property, String value) {
checkProperty(property, value, MAX_LENGTH, PATTERN_NAME);
}
public static void checkHost(String property, String value) {
if (StringUtils.isEmpty(value)) {
return;
}
if (value.startsWith(IPV6_START_MARK) && value.endsWith(IPV6_END_MARK)) {
// if the value start with "[" and end with "]", check whether it is IPV6
try {
InetAddress.getByName(value);
return;
} catch (UnknownHostException e) {
// not a IPv6 string, do nothing, go on to checkName
}
}
checkName(property, value);
}
public static void checkNameHasSymbol(String property, String value) {
checkProperty(property, value, MAX_LENGTH, PATTERN_NAME_HAS_SYMBOL);
}
public static void checkKey(String property, String value) {
checkProperty(property, value, MAX_LENGTH, PATTERN_KEY);
}
public static void checkMultiName(String property, String value) {
checkProperty(property, value, MAX_LENGTH, PATTERN_MULTI_NAME);
}
public static void checkPathName(String property, String value) {
checkProperty(property, value, MAX_PATH_LENGTH, PATTERN_PATH);
}
public static void checkMethodName(String property, String value) {
checkProperty(property, value, MAX_LENGTH, PATTERN_METHOD_NAME);
}
public static void checkParameterName(Map<String, String> parameters) {
if (CollectionUtils.isEmptyMap(parameters)) {
return;
}
List<String> ignoreCheckKeys = new ArrayList<>();
ignoreCheckKeys.add(BACKUP_KEY);
String ignoreCheckKeysStr = parameters.get(IGNORE_CHECK_KEYS);
if (!StringUtils.isBlank(ignoreCheckKeysStr)) {
ignoreCheckKeys.addAll(Arrays.asList(ignoreCheckKeysStr.split(",")));
}
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (!ignoreCheckKeys.contains(entry.getKey())) {
checkNameHasSymbol(entry.getKey(), entry.getValue());
}
}
}
public static void checkProperty(String property, String value, int maxlength, Pattern pattern) {
if (StringUtils.isEmpty(value)) {
return;
}
if (value.length() > maxlength) {
logger.error(
CONFIG_PARAMETER_FORMAT_ERROR,
"the value content is too long",
"",
"Parameter value format error. Invalid " + property + "=\"" + value + "\" is longer than "
+ maxlength);
}
if (pattern != null) {
Matcher matcher = pattern.matcher(value);
if (!matcher.matches()) {
logger.error(
CONFIG_PARAMETER_FORMAT_ERROR,
"the value content is illegal character",
"",
"Parameter value format error. Invalid " + property
+ "=\"" + value + "\" contains illegal "
+ "character, only digit, letter, '-', '_' or '.' is legal.");
}
}
}
}
| 8,611 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.context.ConfigValidator;
public class DefaultConfigValidator implements ConfigValidator {
@Override
public void validate(AbstractConfig config) {
if (config instanceof ProtocolConfig) {
ConfigValidationUtils.validateProtocolConfig((ProtocolConfig) config);
} else if (config instanceof RegistryConfig) {
ConfigValidationUtils.validateRegistryConfig((RegistryConfig) config);
} else if (config instanceof MetadataReportConfig) {
ConfigValidationUtils.validateMetadataConfig((MetadataReportConfig) config);
} else if (config instanceof ProviderConfig) {
ConfigValidationUtils.validateProviderConfig((ProviderConfig) config);
} else if (config instanceof ConsumerConfig) {
ConfigValidationUtils.validateConsumerConfig((ConsumerConfig) config);
} else if (config instanceof ApplicationConfig) {
ConfigValidationUtils.validateApplicationConfig((ApplicationConfig) config);
} else if (config instanceof MonitorConfig) {
ConfigValidationUtils.validateMonitorConfig((MonitorConfig) config);
} else if (config instanceof ModuleConfig) {
ConfigValidationUtils.validateModuleConfig((ModuleConfig) config);
} else if (config instanceof MetricsConfig) {
ConfigValidationUtils.validateMetricsConfig((MetricsConfig) config);
} else if (config instanceof TracingConfig) {
ConfigValidationUtils.validateTracingConfig((TracingConfig) config);
} else if (config instanceof SslConfig) {
ConfigValidationUtils.validateSslConfig((SslConfig) config);
}
}
}
| 8,612 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvoker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.invoker;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
/**
* An invoker wrapper that wrap the invoker and all the metadata (ServiceConfig)
*/
public class DelegateProviderMetaDataInvoker<T> implements Invoker {
protected final Invoker<T> invoker;
private final ServiceConfig<?> metadata;
public DelegateProviderMetaDataInvoker(Invoker<T> invoker, ServiceConfig<?> metadata) {
this.invoker = invoker;
this.metadata = metadata;
}
@Override
public Class<T> getInterface() {
return invoker.getInterface();
}
@Override
public URL getUrl() {
return invoker.getUrl();
}
@Override
public boolean isAvailable() {
return invoker.isAvailable();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void destroy() {
invoker.destroy();
}
public ServiceConfig<?> getMetadata() {
return metadata;
}
}
| 8,613 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.builders.InternalServiceConfigBuilder;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import static java.util.Collections.emptyList;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_METADATA_SERVICE_EXPORTED;
/**
* Export metadata service
*/
public class ConfigurableMetadataServiceExporter {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private MetadataServiceDelegation metadataService;
private volatile ServiceConfig<MetadataService> serviceConfig;
private final ApplicationModel applicationModel;
public ConfigurableMetadataServiceExporter(
ApplicationModel applicationModel, MetadataServiceDelegation metadataService) {
this.applicationModel = applicationModel;
this.metadataService = metadataService;
}
public synchronized ConfigurableMetadataServiceExporter export() {
if (serviceConfig == null || !isExported()) {
ExecutorService internalServiceExecutor = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getInternalServiceExecutor();
this.serviceConfig = InternalServiceConfigBuilder.<MetadataService>newBuilder(applicationModel)
.interfaceClass(MetadataService.class)
.protocol(getApplicationConfig().getMetadataServiceProtocol(), METADATA_SERVICE_PROTOCOL_KEY)
.port(getApplicationConfig().getMetadataServicePort(), METADATA_SERVICE_PORT_KEY)
.registryId("internal-metadata-registry")
.executor(internalServiceExecutor)
.ref(metadataService)
.build(configConsumer -> configConsumer.setMethods(generateMethodConfig()));
// export
serviceConfig.export();
metadataService.setMetadataURL(serviceConfig.getExportedUrls().get(0));
if (logger.isInfoEnabled()) {
logger.info("The MetadataService exports urls : " + serviceConfig.getExportedUrls());
}
} else {
if (logger.isWarnEnabled()) {
logger.warn(
CONFIG_METADATA_SERVICE_EXPORTED,
"",
"",
"The MetadataService has been exported : " + serviceConfig.getExportedUrls());
}
}
return this;
}
public ConfigurableMetadataServiceExporter unexport() {
if (isExported()) {
serviceConfig.unexport();
metadataService.setMetadataURL(null);
}
return this;
}
public boolean isExported() {
return serviceConfig != null && serviceConfig.isExported() && !serviceConfig.isUnexported();
}
private ApplicationConfig getApplicationConfig() {
return applicationModel.getApplicationConfigManager().getApplication().get();
}
/**
* Generate Method Config for Service Discovery Metadata <p/>
* <p>
* Make {@link MetadataService} support argument callback,
* used to notify {@link org.apache.dubbo.registry.client.ServiceInstance}'s
* metadata change event
*
* @since 3.0
*/
private List<MethodConfig> generateMethodConfig() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("getAndListenInstanceMetadata");
ArgumentConfig argumentConfig = new ArgumentConfig();
argumentConfig.setIndex(1);
argumentConfig.setCallback(true);
methodConfig.setArguments(Collections.singletonList(argumentConfig));
return Collections.singletonList(methodConfig);
}
// for unit test
public void setMetadataService(MetadataServiceDelegation metadataService) {
this.metadataService = metadataService;
}
// for unit test
public List<URL> getExportedURLs() {
return serviceConfig != null ? serviceConfig.getExportedUrls() : emptyList();
}
}
| 8,614 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.registry.client.metadata.SpringCloudMetadataServiceURLBuilder;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceParameter;
/**
* Used to interact with non-dubbo systems, also see {@link SpringCloudMetadataServiceURLBuilder}
*/
public class MetadataServiceURLParamsMetadataCustomizer implements ServiceInstanceCustomizer {
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
Map<String, String> metadata = serviceInstance.getMetadata();
String propertyName = resolveMetadataPropertyName(serviceInstance);
String propertyValue = resolveMetadataPropertyValue(applicationModel);
if (!isBlank(propertyName) && !isBlank(propertyValue)) {
metadata.put(propertyName, propertyValue);
}
}
private String resolveMetadataPropertyName(ServiceInstance serviceInstance) {
return METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
}
private String resolveMetadataPropertyValue(ApplicationModel applicationModel) {
ModuleServiceRepository serviceRepository =
applicationModel.getInternalModule().getServiceRepository();
String key = BaseServiceMetadata.buildServiceKey(
MetadataService.class.getName(), applicationModel.getApplicationName(), MetadataService.VERSION);
ProviderModel providerModel = serviceRepository.lookupExportedService(key);
String metadataValue = "";
if (providerModel != null) {
List<URL> metadataURLs = providerModel.getServiceUrls();
if (CollectionUtils.isNotEmpty(metadataURLs)) {
metadataValue = getMetadataServiceParameter(metadataURLs.get(0));
}
}
return metadataValue;
}
}
| 8,615 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.deploy.ApplicationDeployListener;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
public class ExporterDeployListener implements ApplicationDeployListener, Prioritized {
protected volatile ConfigurableMetadataServiceExporter metadataServiceExporter;
@Override
public void onInitialize(ApplicationModel scopeModel) {}
@Override
public void onStarting(ApplicationModel scopeModel) {}
@Override
public synchronized void onStarted(ApplicationModel applicationModel) {}
@Override
public synchronized void onStopping(ApplicationModel scopeModel) {}
private String getMetadataType(ApplicationModel applicationModel) {
String type = applicationModel
.getApplicationConfigManager()
.getApplicationOrElseThrow()
.getMetadataType();
if (StringUtils.isEmpty(type)) {
type = DEFAULT_METADATA_STORAGE_TYPE;
}
return type;
}
private String getRegisterMode(ApplicationModel applicationModel) {
String type = applicationModel
.getApplicationConfigManager()
.getApplicationOrElseThrow()
.getRegisterMode();
if (StringUtils.isEmpty(type)) {
type = DEFAULT_REGISTER_MODE;
}
return type;
}
public ConfigurableMetadataServiceExporter getMetadataServiceExporter() {
return metadataServiceExporter;
}
public void setMetadataServiceExporter(ConfigurableMetadataServiceExporter metadataServiceExporter) {
this.metadataServiceExporter = metadataServiceExporter;
}
@Override
public synchronized void onModuleStarted(ApplicationModel applicationModel) {
// start metadata service exporter
MetadataServiceDelegation metadataService =
applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class);
if (metadataServiceExporter == null) {
metadataServiceExporter = new ConfigurableMetadataServiceExporter(applicationModel, metadataService);
// fixme, let's disable local metadata service export at this moment
if (!REMOTE_METADATA_STORAGE_TYPE.equals(getMetadataType(applicationModel))
&& !INTERFACE_REGISTER_MODE.equals(getRegisterMode(applicationModel))) {
metadataServiceExporter.export();
}
}
}
@Override
public synchronized void onStopped(ApplicationModel scopeModel) {
if (metadataServiceExporter != null && metadataServiceExporter.isExported()) {
try {
metadataServiceExporter.unexport();
} catch (Exception ignored) {
// ignored
}
}
}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {}
@Override
public int getPriority() {
return MAX_PRIORITY;
}
}
| 8,616 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/EmbeddedZooKeeper.java
|
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.common.utils.TestSocketUtils;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.springframework.context.SmartLifecycle;
import org.springframework.util.ErrorHandler;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.UUID;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_INIT_ZOOKEEPER_SERVER_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER;
/**
* from: https://github.com/spring-projects/spring-xd/blob/v1.3.1.RELEASE/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/zookeeper/ZooKeeperUtils.java
* <p>
* Helper class to start an embedded instance of standalone (non clustered) ZooKeeper.
* <p>
* NOTE: at least an external standalone server (if not an ensemble) are recommended, even for
* {@link org.springframework.xd.dirt.server.singlenode.SingleNodeApplication}
*/
public class EmbeddedZooKeeper implements SmartLifecycle {
/**
* Logger.
*/
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EmbeddedZooKeeper.class);
/**
* ZooKeeper client port. This will be determined dynamically upon startup.
*/
private final int clientPort;
/**
* Whether to auto-start. Default is true.
*/
private boolean autoStartup = true;
/**
* Lifecycle phase. Default is 0.
*/
private int phase = 0;
/**
* Thread for running the ZooKeeper server.
*/
private volatile Thread zkServerThread;
/**
* ZooKeeper server.
*/
private volatile ZooKeeperServerMain zkServer;
/**
* {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread.
*/
private ErrorHandler errorHandler;
private boolean daemon = true;
/**
* Construct an EmbeddedZooKeeper with a random port.
*/
public EmbeddedZooKeeper() {
clientPort = TestSocketUtils.findAvailableTcpPort();
}
/**
* Construct an EmbeddedZooKeeper with the provided port.
*
* @param clientPort port for ZooKeeper server to bind to
*/
public EmbeddedZooKeeper(int clientPort, boolean daemon) {
this.clientPort = clientPort;
this.daemon = daemon;
}
/**
* Returns the port that clients should use to connect to this embedded server.
*
* @return dynamically determined client port
*/
public int getClientPort() {
return this.clientPort;
}
/**
* Specify whether to start automatically. Default is true.
*
* @param autoStartup whether to start automatically
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}
/**
* Specify the lifecycle phase for the embedded server.
*
* @param phase the lifecycle phase
*/
public void setPhase(int phase) {
this.phase = phase;
}
/**
* {@inheritDoc}
*/
@Override
public int getPhase() {
return this.phase;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRunning() {
return (zkServerThread != null);
}
/**
* Start the ZooKeeper server in a background thread.
* <p>
* Register an error handler via {@link #setErrorHandler} in order to handle
* any exceptions thrown during startup or execution.
*/
@Override
public synchronized void start() {
if (zkServerThread == null) {
zkServerThread = new Thread(new ServerRunnable(), "ZooKeeper Server Starter");
zkServerThread.setDaemon(daemon);
zkServerThread.start();
}
}
/**
* Shutdown the ZooKeeper server.
*/
@Override
public synchronized void stop() {
if (zkServerThread != null) {
// The shutdown method is protected...thus this hack to invoke it.
// This will log an exception on shutdown; see
// https://issues.apache.org/jira/browse/ZOOKEEPER-1873 for details.
try {
Method shutdown = ZooKeeperServerMain.class.getDeclaredMethod("shutdown");
shutdown.setAccessible(true);
shutdown.invoke(zkServer);
} catch (Exception e) {
throw new RuntimeException(e);
}
// It is expected that the thread will exit after
// the server is shutdown; this will block until
// the shutdown is complete.
try {
zkServerThread.join(5000);
zkServerThread = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.warn(TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER, "", "", "Interrupted while waiting for embedded ZooKeeper to exit");
// abandoning zk thread
zkServerThread = null;
}
}
}
/**
* Stop the server if running and invoke the callback when complete.
*/
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
/**
* Provide an {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread. If none
* is provided, only error-level logging will occur.
*
* @param errorHandler the {@link ErrorHandler} to be invoked
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Runnable implementation that starts the ZooKeeper server.
*/
private class ServerRunnable implements Runnable {
@Override
public void run() {
try {
Properties properties = new Properties();
File file = new File(System.getProperty("java.io.tmpdir")
+ File.separator + UUID.randomUUID());
file.deleteOnExit();
properties.setProperty("dataDir", file.getAbsolutePath());
properties.setProperty("clientPort", String.valueOf(clientPort));
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
quorumPeerConfig.parseProperties(properties);
zkServer = new ZooKeeperServerMain();
ServerConfig configuration = new ServerConfig();
configuration.readFrom(quorumPeerConfig);
zkServer.runFromConfig(configuration);
} catch (Exception e) {
if (errorHandler != null) {
errorHandler.handleError(e);
} else {
logger.error(TESTING_INIT_ZOOKEEPER_SERVER_ERROR, "ZooKeeper server error", "", "Exception running embedded ZooKeeper.", e);
}
}
}
}
}
| 8,617 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/DubboStateListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.config.spring.context.event.DubboApplicationStateEvent;
import org.springframework.context.ApplicationListener;
public class DubboStateListener implements ApplicationListener<DubboApplicationStateEvent> {
private DeployState state;
@Override
public void onApplicationEvent(DubboApplicationStateEvent event) {
state = event.getState();
}
public DeployState getState() {
return state;
}
}
| 8,618 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/JavaConfigBeanTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.util.Collection;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class JavaConfigBeanTest {
private static final String MY_PROTOCOL_ID = "myProtocol";
private static final String MY_REGISTRY_ID = "my-registry";
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
}
@AfterEach
public void afterEach() {
SysProps.clear();
}
@Test
void testBean() {
SysProps.setProperty("dubbo.application.owner", "Tom");
SysProps.setProperty("dubbo.application.qos-enable", "false");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "2346");
String registryAddress = ZookeeperRegistryCenterConfig.getConnectionAddress();
SysProps.setProperty("dubbo.registry.address", registryAddress);
SysProps.setProperty("dubbo.provider.group", "test");
AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(
TestConfiguration.class, ConsumerConfiguration.class, ProviderConfiguration.class);
try {
consumerContext.start();
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
ApplicationConfig application = configManager.getApplication().get();
Assertions.assertEquals(false, application.getQosEnable());
Assertions.assertEquals("Tom", application.getOwner());
RegistryConfig registry = configManager.getRegistry(MY_REGISTRY_ID).get();
Assertions.assertEquals(registryAddress, registry.getAddress());
Collection<ProtocolConfig> protocols = configManager.getProtocols();
Assertions.assertEquals(1, protocols.size());
ProtocolConfig protocolConfig = protocols.iterator().next();
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(2346, protocolConfig.getPort());
Assertions.assertEquals(MY_PROTOCOL_ID, protocolConfig.getId());
ApplicationModel applicationModel = consumerContext.getBean(ApplicationModel.class);
ModuleConfigManager moduleConfigManager =
applicationModel.getDefaultModule().getConfigManager();
ConsumerConfig consumerConfig =
moduleConfigManager.getDefaultConsumer().get();
Assertions.assertEquals(1000, consumerConfig.getTimeout());
Assertions.assertEquals("demo", consumerConfig.getGroup());
Assertions.assertEquals(false, consumerConfig.isCheck());
Assertions.assertEquals(2, consumerConfig.getRetries());
Map<String, ReferenceBean> referenceBeanMap = consumerContext.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&demoService");
Assertions.assertNotNull(referenceBean);
ReferenceConfig referenceConfig = referenceBean.getReferenceConfig();
// use consumer's attributes as default value
Assertions.assertEquals(consumerConfig.getTimeout(), referenceConfig.getTimeout());
Assertions.assertEquals(consumerConfig.getGroup(), referenceConfig.getGroup());
// consumer cannot override reference's attribute
Assertions.assertEquals(5, referenceConfig.getRetries());
DemoService referProxy = (DemoService) referenceConfig.get();
Assertions.assertTrue(referProxy instanceof DemoService);
String result = referProxy.sayName("dubbo");
Assertions.assertEquals("say:dubbo", result);
} finally {
consumerContext.close();
}
}
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.annotation.consumer")
@Configuration
static class TestConfiguration {
@Bean("dubbo-demo-application")
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo-demo-application");
return applicationConfig;
}
@Bean(MY_PROTOCOL_ID)
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("rest");
protocolConfig.setPort(1234);
return protocolConfig;
}
@Bean(MY_REGISTRY_ID)
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
return registryConfig;
}
@Bean
public ConsumerConfig consumerConfig() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setTimeout(1000);
consumer.setGroup("demo");
consumer.setCheck(false);
consumer.setRetries(2);
return consumer;
}
}
@Configuration
static class ConsumerConfiguration {
@Bean
@DubboReference(scope = Constants.SCOPE_LOCAL, retries = 5)
public ReferenceBean<DemoService> demoService() {
return new ReferenceBean<>();
}
}
@Configuration
static class ProviderConfiguration {
@Bean
@DubboService(group = "demo")
public DemoService demoServiceImpl() {
return new DemoServiceImpl();
}
}
}
| 8,619 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.RpcContext;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* SimpleRegistryService
*/
public class SimpleRegistryService extends AbstractRegistryService {
private static final Logger logger = LoggerFactory.getLogger(SimpleRegistryService.class);
private final ConcurrentMap<String, ConcurrentMap<String, URL>> remoteRegistered =
new ConcurrentHashMap<String, ConcurrentMap<String, URL>>();
private final ConcurrentMap<String, ConcurrentMap<String, NotifyListener>> remoteListeners =
new ConcurrentHashMap<String, ConcurrentMap<String, NotifyListener>>();
private List<String> registries;
@Override
public void register(String service, URL url) {
super.register(service, url);
String client = RpcContext.getServiceContext().getRemoteAddressString();
Map<String, URL> urls =
ConcurrentHashMapUtils.computeIfAbsent(remoteRegistered, client, k -> new ConcurrentHashMap<>());
urls.put(service, url);
notify(service, getRegistered().get(service));
}
@Override
public void unregister(String service, URL url) {
super.unregister(service, url);
String client = RpcContext.getServiceContext().getRemoteAddressString();
Map<String, URL> urls = remoteRegistered.get(client);
if (urls != null && urls.size() > 0) {
urls.remove(service);
}
notify(service, getRegistered().get(service));
}
@Override
public void subscribe(String service, URL url, NotifyListener listener) {
String client = RpcContext.getServiceContext().getRemoteAddressString();
if (logger.isInfoEnabled()) {
logger.info("[subscribe] service: " + service + ",client:" + client);
}
List<URL> urls = getRegistered().get(service);
if ((RegistryService.class.getName() + ":0.0.0").equals(service) && CollectionUtils.isEmpty(urls)) {
register(
service,
new ServiceConfigURL(
"dubbo",
NetUtils.getLocalHost(),
RpcContext.getServiceContext().getLocalPort(),
RegistryService.class.getName(),
url.getParameters()));
List<String> rs = registries;
if (rs != null && rs.size() > 0) {
for (String registry : rs) {
register(service, UrlUtils.parseURL(registry, url.getParameters()));
}
}
}
super.subscribe(service, url, listener);
Map<String, NotifyListener> listeners =
ConcurrentHashMapUtils.computeIfAbsent(remoteListeners, client, k -> new ConcurrentHashMap<>());
listeners.put(service, listener);
urls = getRegistered().get(service);
if (urls != null && urls.size() > 0) {
listener.notify(urls);
}
}
@Override
public void unsubscribe(String service, URL url, NotifyListener listener) {
super.unsubscribe(service, url, listener);
String client = RpcContext.getServiceContext().getRemoteAddressString();
Map<String, NotifyListener> listeners = remoteListeners.get(client);
if (listeners != null && listeners.size() > 0) {
listeners.remove(service);
}
List<URL> urls = getRegistered().get(service);
if (urls != null && urls.size() > 0) {
listener.notify(urls);
}
}
public void disconnect() {
String client = RpcContext.getServiceContext().getRemoteAddressString();
if (logger.isInfoEnabled()) {
logger.info("Disconnected " + client);
}
ConcurrentMap<String, URL> urls = remoteRegistered.get(client);
if (urls != null && urls.size() > 0) {
for (Map.Entry<String, URL> entry : urls.entrySet()) {
super.unregister(entry.getKey(), entry.getValue());
}
}
Map<String, NotifyListener> listeners = remoteListeners.get(client);
if (listeners != null && listeners.size() > 0) {
for (Map.Entry<String, NotifyListener> entry : listeners.entrySet()) {
String service = entry.getKey();
super.unsubscribe(
service,
new ServiceConfigURL(
"subscribe",
RpcContext.getServiceContext().getRemoteHost(),
RpcContext.getServiceContext().getRemotePort(),
RegistryService.class.getName(),
getSubscribed(service)),
entry.getValue());
}
}
}
public List<String> getRegistries() {
return registries;
}
public void setRegistries(List<String> registries) {
this.registries = registries;
}
}
| 8,620 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ControllerServiceConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.spring.api.SpringControllerService;
import org.junit.jupiter.api.Test;
public class ControllerServiceConfigTest {
@Test
void testServiceConfig() {
ServiceConfig<SpringControllerService> serviceServiceConfig = new ServiceConfig<>();
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo");
serviceServiceConfig.setApplication(applicationConfig);
serviceServiceConfig.setProtocol(new ProtocolConfig("rest", 8080));
serviceServiceConfig.setRef(new SpringControllerService());
serviceServiceConfig.setInterface(SpringControllerService.class.getName());
serviceServiceConfig.export();
serviceServiceConfig.unexport();
}
}
| 8,621 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ServiceBeanTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.mockito.Mockito.mock;
class ServiceBeanTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
DubboBootstrap.reset();
}
@Test
void testGetService() {
TestService service = mock(TestService.class);
ServiceBean serviceBean = new ServiceBean(null, service);
Service beanService = serviceBean.getService();
MatcherAssert.assertThat(beanService, not(nullValue()));
}
abstract class TestService implements Service {}
}
| 8,622 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/ConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.action.DemoActionByAnnotation;
import org.apache.dubbo.config.spring.action.DemoActionBySetter;
import org.apache.dubbo.config.spring.annotation.consumer.AnnotationAction;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration;
import org.apache.dubbo.config.spring.filter.MockFilter;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.config.spring.impl.HelloServiceImpl;
import org.apache.dubbo.config.spring.impl.NotifyService;
import org.apache.dubbo.config.spring.registry.MockRegistry;
import org.apache.dubbo.config.spring.registry.MockRegistryFactory;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.service.GenericService;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* ConfigTest
*/
class ConfigTest {
private static String resourcePath = ConfigTest.class.getPackage().getName().replace('.', '/');
@BeforeEach
public void setUp() {
SysProps.clear();
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
SysProps.clear();
DubboBootstrap.reset();
}
@Test
@Disabled("waiting-to-fix")
public void testSpringExtensionInject() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/spring-extension-inject.xml");
try {
ctx.start();
MockFilter filter = (MockFilter)
ExtensionLoader.getExtensionLoader(Filter.class).getExtension("mymock");
assertNotNull(filter.getMockDao());
assertNotNull(filter.getProtocol());
assertNotNull(filter.getLoadBalance());
} finally {
ctx.stop();
ctx.close();
}
}
@Test
void testServiceClass() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/service-class.xml");
try {
ctx.start();
DemoService demoService = refer("dubbo://127.0.0.1:20887");
String hello = demoService.sayName("hello");
assertEquals("welcome:hello", hello);
} finally {
ctx.stop();
ctx.close();
}
}
@Test
@Disabled("waiting-to-fix")
public void testServiceAnnotation() {
DubboBootstrap consumerBootstrap = null;
AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext();
try {
providerContext.register(ProviderConfiguration.class);
providerContext.refresh();
ReferenceConfig<HelloService> reference = new ReferenceConfig<HelloService>();
reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
reference.setInterface(HelloService.class);
reference.setUrl("dubbo://127.0.0.1:12345");
consumerBootstrap = DubboBootstrap.newInstance()
.application(new ApplicationConfig("consumer"))
.reference(reference)
.start();
HelloService helloService = consumerBootstrap.getCache().get(reference);
String hello = helloService.sayHello("hello");
assertEquals("Hello, hello", hello);
} finally {
providerContext.close();
if (consumerBootstrap != null) {
consumerBootstrap.stop();
}
}
}
@Test
@SuppressWarnings("unchecked")
public void testProviderNestedService() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml");
try {
ctx.start();
ServiceConfig<DemoService> serviceConfig = (ServiceConfig<DemoService>) ctx.getBean("serviceConfig");
assertNotNull(serviceConfig.getProvider());
assertEquals(2000, serviceConfig.getProvider().getTimeout().intValue());
ServiceConfig<DemoService> serviceConfig2 = (ServiceConfig<DemoService>) ctx.getBean("serviceConfig2");
assertNotNull(serviceConfig2.getProvider());
assertEquals(1000, serviceConfig2.getProvider().getTimeout().intValue());
} finally {
ctx.stop();
ctx.close();
}
}
private DemoService refer(String url) {
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
reference.setInterface(DemoService.class);
reference.setUrl(url);
DubboBootstrap bootstrap = DubboBootstrap.newInstance()
.application(new ApplicationConfig("consumer"))
.reference(reference)
.start();
return bootstrap.getCache().get(reference);
}
@Test
@Disabled("waiting-to-fix")
public void testToString() {
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setApplication(new ApplicationConfig("consumer"));
reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:20881");
String str = reference.toString();
assertTrue(str.startsWith("<dubbo:reference "));
assertTrue(str.contains(" url=\"dubbo://127.0.0.1:20881\" "));
assertTrue(str.contains(" interface=\"org.apache.dubbo.config.spring.api.DemoService\" "));
assertTrue(str.endsWith(" />"));
}
@Test
@Disabled("waiting-to-fix")
public void testForks() {
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setApplication(new ApplicationConfig("consumer"));
reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:20881");
int forks = 10;
reference.setForks(forks);
String str = reference.toString();
assertTrue(str.contains("forks=\"" + forks + "\""));
}
@Test
void testMultiProtocol() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol.xml");
try {
ctx.start();
DemoService demoService = refer("dubbo://127.0.0.1:20881");
String hello = demoService.sayName("hello");
assertEquals("say:hello", hello);
} finally {
ctx.stop();
ctx.close();
}
}
@Test
@Disabled("waiting-to-fix")
public void testMultiProtocolDefault() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-default.xml");
try {
ctx.start();
DemoService demoService = refer("rmi://127.0.0.1:10991");
String hello = demoService.sayName("hello");
assertEquals("say:hello", hello);
} finally {
ctx.stop();
ctx.close();
}
}
@Test
@Disabled("waiting-to-fix")
public void testMultiProtocolError() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-error.xml");
try {
ctx.start();
ctx.stop();
ctx.close();
fail();
} catch (BeanCreationException e) {
assertTrue(e.getMessage().contains("Found multi-protocols"));
} finally {
try {
ctx.close();
} catch (Exception e) {
}
}
}
@Test
@Disabled("waiting-to-fix")
public void testMultiProtocolRegister() {
SimpleRegistryService registryService = new SimpleRegistryService();
Exporter<RegistryService> exporter = SimpleRegistryExporter.export(4547, registryService);
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol-register.xml");
try {
ctx.start();
List<URL> urls = registryService.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService");
assertNotNull(urls);
assertEquals(1, urls.size());
assertEquals(
"dubbo://" + NetUtils.getLocalHost() + ":20824/org.apache.dubbo.config.spring.api.DemoService",
urls.get(0).toIdentityString());
} finally {
ctx.stop();
ctx.close();
exporter.unexport();
}
}
@Test
@Disabled("waiting-to-fix")
public void testMultiRegistry() {
SimpleRegistryService registryService1 = new SimpleRegistryService();
Exporter<RegistryService> exporter1 = SimpleRegistryExporter.export(4545, registryService1);
SimpleRegistryService registryService2 = new SimpleRegistryService();
Exporter<RegistryService> exporter2 = SimpleRegistryExporter.export(4546, registryService2);
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-registry.xml");
try {
ctx.start();
List<URL> urls1 = registryService1.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService");
assertNull(urls1);
List<URL> urls2 = registryService2.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService");
assertNotNull(urls2);
assertEquals(1, urls2.size());
assertEquals(
"dubbo://" + NetUtils.getLocalHost() + ":20880/org.apache.dubbo.config.spring.api.DemoService",
urls2.get(0).toIdentityString());
} finally {
ctx.stop();
ctx.close();
exporter1.unexport();
exporter2.unexport();
}
}
@Test
@Disabled("waiting-to-fix")
public void testDelayFixedTime() throws Exception {
SimpleRegistryService registryService = new SimpleRegistryService();
Exporter<RegistryService> exporter = SimpleRegistryExporter.export(4548, registryService);
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/delay-fixed-time.xml");
try {
ctx.start();
List<URL> urls = registryService.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService");
assertNull(urls);
int i = 0;
while ((i++) < 60 && urls == null) {
urls = registryService.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService");
Thread.sleep(10);
}
assertNotNull(urls);
assertEquals(1, urls.size());
assertEquals(
"dubbo://" + NetUtils.getLocalHost() + ":20888/org.apache.dubbo.config.spring.api.DemoService",
urls.get(0).toIdentityString());
} finally {
ctx.stop();
ctx.close();
exporter.unexport();
}
}
@Test
@Disabled("waiting-to-fix")
public void testDelayOnInitialized() throws Exception {
SimpleRegistryService registryService = new SimpleRegistryService();
Exporter<RegistryService> exporter = SimpleRegistryExporter.export(4548, registryService);
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/delay-on-initialized.xml");
try {
// ctx.start();
List<URL> urls = registryService.getRegistered().get("org.apache.dubbo.config.spring.api.DemoService");
assertNotNull(urls);
assertEquals(1, urls.size());
assertEquals(
"dubbo://" + NetUtils.getLocalHost() + ":20888/org.apache.dubbo.config.spring.api.DemoService",
urls.get(0).toIdentityString());
} finally {
ctx.stop();
ctx.close();
exporter.unexport();
}
}
@Test
void testRmiTimeout() throws Exception {
System.clearProperty("sun.rmi.transport.tcp.responseTimeout");
ConsumerConfig consumer = new ConsumerConfig();
consumer.setTimeout(1000);
assertEquals("1000", System.getProperty("sun.rmi.transport.tcp.responseTimeout"));
consumer.setTimeout(2000);
assertEquals("1000", System.getProperty("sun.rmi.transport.tcp.responseTimeout"));
}
@Test
@Disabled("waiting-to-fix")
public void testAutowireAndAOP() throws Exception {
ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml");
try {
providerContext.start();
ClassPathXmlApplicationContext byNameContext =
new ClassPathXmlApplicationContext(resourcePath + "/aop-autowire-byname.xml");
try {
byNameContext.start();
DemoActionBySetter demoActionBySetter =
(DemoActionBySetter) byNameContext.getBean("demoActionBySetter");
assertNotNull(demoActionBySetter.getDemoService());
assertEquals(
"aop:say:hello", demoActionBySetter.getDemoService().sayName("hello"));
DemoActionByAnnotation demoActionByAnnotation =
(DemoActionByAnnotation) byNameContext.getBean("demoActionByAnnotation");
assertNotNull(demoActionByAnnotation.getDemoService());
assertEquals(
"aop:say:hello", demoActionByAnnotation.getDemoService().sayName("hello"));
} finally {
byNameContext.stop();
byNameContext.close();
}
ClassPathXmlApplicationContext byTypeContext =
new ClassPathXmlApplicationContext(resourcePath + "/aop-autowire-bytype.xml");
try {
byTypeContext.start();
DemoActionBySetter demoActionBySetter =
(DemoActionBySetter) byTypeContext.getBean("demoActionBySetter");
assertNotNull(demoActionBySetter.getDemoService());
assertEquals(
"aop:say:hello", demoActionBySetter.getDemoService().sayName("hello"));
DemoActionByAnnotation demoActionByAnnotation =
(DemoActionByAnnotation) byTypeContext.getBean("demoActionByAnnotation");
assertNotNull(demoActionByAnnotation.getDemoService());
assertEquals(
"aop:say:hello", demoActionByAnnotation.getDemoService().sayName("hello"));
} finally {
byTypeContext.stop();
byTypeContext.close();
}
} finally {
providerContext.stop();
providerContext.close();
}
}
@Test
void testAppendFilter() throws Exception {
ApplicationConfig application = new ApplicationConfig("provider");
ProviderConfig provider = new ProviderConfig();
provider.setFilter("classloader,monitor");
ConsumerConfig consumer = new ConsumerConfig();
consumer.setFilter("classloader,monitor");
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setFilter("accesslog,trace");
service.setProvider(provider);
service.setProtocol(new ProtocolConfig("dubbo", 20880));
service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setFilter("accesslog,trace");
reference.setConsumer(consumer);
reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
reference.setInterface(DemoService.class);
reference.setUrl(
"dubbo://" + NetUtils.getLocalHost() + ":20880?" + DemoService.class.getName() + "?check=false");
try {
DubboBootstrap.getInstance()
.application(application)
.provider(provider)
.service(service)
.reference(reference)
.start();
List<URL> urls = service.getExportedUrls();
assertNotNull(urls);
assertEquals(1, urls.size());
assertEquals("classloader,monitor,accesslog,trace", urls.get(0).getParameter("service.filter"));
urls = reference.getExportedUrls();
assertNotNull(urls);
assertEquals(1, urls.size());
assertEquals("classloader,monitor,accesslog,trace", urls.get(0).getParameter("reference.filter"));
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testInitReference() throws Exception {
ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml");
try {
providerContext.start();
// consumer app
ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(
resourcePath + "/init-reference.xml", resourcePath + "/init-reference-properties.xml");
try {
consumerContext.start();
NotifyService notifyService = consumerContext.getBean(NotifyService.class);
// check reference bean
Map<String, ReferenceBean> referenceBeanMap = consumerContext.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(2, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&demoService");
Assertions.assertNotNull(referenceBean);
ReferenceConfig referenceConfig = referenceBean.getReferenceConfig();
// reference parameters
Assertions.assertNotNull(referenceConfig.getParameters().get("connec.timeout"));
Assertions.assertEquals("demo_tag", referenceConfig.getTag());
// methods
Assertions.assertEquals(1, referenceConfig.getMethods().size());
MethodConfig methodConfig = referenceConfig.getMethods().get(0);
Assertions.assertEquals("sayName", methodConfig.getName());
Assertions.assertEquals(notifyService, methodConfig.getOninvoke());
Assertions.assertEquals(notifyService, methodConfig.getOnreturn());
Assertions.assertEquals(notifyService, methodConfig.getOnthrow());
Assertions.assertEquals("onInvoke", methodConfig.getOninvokeMethod());
Assertions.assertEquals("onReturn", methodConfig.getOnreturnMethod());
Assertions.assertEquals("onThrow", methodConfig.getOnthrowMethod());
// method arguments
Assertions.assertEquals(1, methodConfig.getArguments().size());
ArgumentConfig argumentConfig = methodConfig.getArguments().get(0);
Assertions.assertEquals(0, argumentConfig.getIndex());
Assertions.assertEquals(true, argumentConfig.isCallback());
// method parameters
Assertions.assertEquals(1, methodConfig.getParameters().size());
Assertions.assertEquals("my-token", methodConfig.getParameters().get("access-token"));
// do call
DemoService demoService = (DemoService) consumerContext.getBean("demoService");
assertEquals("say:world", demoService.sayName("world"));
GenericService demoService2 = (GenericService) consumerContext.getBean("demoService2");
assertEquals(
"say:world",
demoService2.$invoke("sayName", new String[] {"java.lang.String"}, new Object[] {"world"}));
} finally {
consumerContext.stop();
consumerContext.close();
}
} finally {
providerContext.stop();
providerContext.close();
}
}
// DUBBO-571 methods key in provider's URLONE doesn't contain the methods from inherited super interface
@Test
void test_noMethodInterface_methodsKeyHasValue() throws Exception {
List<URL> urls = null;
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-no-methods-interface.xml");
try {
ctx.start();
ServiceBean bean = (ServiceBean) ctx.getBean("service");
urls = bean.getExportedUrls();
assertEquals(1, urls.size());
URL url = urls.get(0);
assertEquals("getBox,sayName", url.getParameter("methods"));
} finally {
ctx.stop();
ctx.close();
// Check if the port is closed
if (urls != null) {
for (URL url : urls) {
Assertions.assertFalse(NetUtils.isPortInUsed(url.getPort()));
}
}
}
}
// DUBBO-147 find all invoker instances which have been tried from RpcContext
@Disabled("waiting-to-fix")
@Test
void test_RpcContext_getUrls() throws Exception {
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-long-waiting.xml");
try {
providerContext.start();
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/init-reference-getUrls.xml");
try {
ctx.start();
DemoService demoService = (DemoService) ctx.getBean("demoService");
try {
demoService.sayName("Haha");
fail();
} catch (RpcException expected) {
assertThat(expected.getMessage(), containsString("Tried 3 times"));
}
assertEquals(3, RpcContext.getServiceContext().getUrls().size());
} finally {
ctx.stop();
ctx.close();
}
} finally {
providerContext.stop();
providerContext.close();
}
}
// BUG: DUBBO-846 in version 2.0.9, config retry="false" on provider's method doesn't work
@Test
@Disabled("waiting-to-fix")
public void test_retrySettingFail() throws Exception {
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-long-waiting.xml");
try {
providerContext.start();
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/init-reference-retry-false.xml");
try {
ctx.start();
DemoService demoService = (DemoService) ctx.getBean("demoService");
try {
demoService.sayName("Haha");
fail();
} catch (RpcException expected) {
assertThat(expected.getMessage(), containsString("Tried 1 times"));
}
assertEquals(1, RpcContext.getServiceContext().getUrls().size());
} finally {
ctx.stop();
ctx.close();
}
} finally {
providerContext.stop();
providerContext.close();
}
}
// BuG: DUBBO-146 Provider doesn't have exception output, and consumer has timeout error when serialization fails
// for example, object transported on the wire doesn't implement Serializable
@Test
@Disabled("waiting-to-fix")
public void test_returnSerializationFail() throws Exception {
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/demo-provider-UnserializableBox.xml");
try {
providerContext.start();
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
resourcePath + "/init-reference.xml", resourcePath + "/init-reference-properties.xml");
try {
ctx.start();
DemoService demoService = (DemoService) ctx.getBean("demoService");
try {
demoService.getBox();
fail();
} catch (RpcException expected) {
assertThat(expected.getMessage(), containsString("must implement java.io.Serializable"));
}
} finally {
ctx.stop();
ctx.close();
}
} finally {
providerContext.stop();
providerContext.close();
}
}
@Test
@Disabled("waiting-to-fix")
public void testXmlOverrideProperties() throws Exception {
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/xml-override-properties.xml");
try {
providerContext.start();
ApplicationConfig application = (ApplicationConfig) providerContext.getBean("application");
assertEquals("demo-provider", application.getName());
assertEquals("world", application.getOwner());
RegistryConfig registry = (RegistryConfig) providerContext.getBean("registry");
assertEquals("N/A", registry.getAddress());
ProtocolConfig dubbo = (ProtocolConfig) providerContext.getBean("dubbo");
assertEquals(20813, dubbo.getPort().intValue());
} finally {
providerContext.stop();
providerContext.close();
}
}
@Test
@Disabled("waiting-to-fix")
public void testApiOverrideProperties() throws Exception {
ApplicationConfig application = new ApplicationConfig();
application.setName("api-override-properties");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("dubbo");
protocol.setPort(13123);
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setRegistry(registry);
service.setProtocol(protocol);
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
reference.setInterface(DemoService.class);
reference.setUrl("dubbo://127.0.0.1:13123");
try {
DubboBootstrap.getInstance()
.application(application)
.registry(registry)
.protocol(protocol)
.service(service)
.reference(reference)
.start();
URL url = service.getExportedUrls().get(0);
assertEquals("api-override-properties", url.getParameter("application"));
assertEquals("world", url.getParameter("owner"));
assertEquals(13123, url.getPort());
url = reference.getExportedUrls().get(0);
assertEquals("2000", url.getParameter("timeout"));
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testSystemPropertyOverrideProtocol() throws Exception {
SysProps.setProperty("dubbo.protocols.tri.port", ""); // empty config should be ignored
SysProps.setProperty("dubbo.protocols.dubbo.port", "20812"); // override success
SysProps.setProperty("dubbo.protocol.port", "20899"); // override fail
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml");
try {
providerContext.start();
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
ProtocolConfig protocol = configManager.getProtocol("dubbo").get();
assertEquals(20812, protocol.getPort());
} finally {
providerContext.close();
}
}
@Test
void testSystemPropertyOverrideMultiProtocol() throws Exception {
SysProps.setProperty("dubbo.protocols.dubbo.port", "20814");
SysProps.setProperty("dubbo.protocols.tri.port", "10914");
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/override-multi-protocol.xml");
try {
providerContext.start();
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
ProtocolConfig dubboProtocol = configManager.getProtocol("dubbo").get();
assertEquals(20814, dubboProtocol.getPort().intValue());
ProtocolConfig tripleProtocol = configManager.getProtocol("tri").get();
assertEquals(10914, tripleProtocol.getPort().intValue());
} finally {
providerContext.stop();
providerContext.close();
}
}
@SuppressWarnings("unchecked")
@Test
@Disabled("waiting-to-fix")
public void testSystemPropertyOverrideXmlDefault() throws Exception {
SysProps.setProperty("dubbo.application.name", "sysover");
SysProps.setProperty("dubbo.application.owner", "sysowner");
SysProps.setProperty("dubbo.registry.address", "N/A");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "20819");
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/system-properties-override-default.xml");
try {
providerContext.start();
ServiceConfig<DemoService> service =
(ServiceConfig<DemoService>) providerContext.getBean("demoServiceConfig");
assertEquals("sysover", service.getApplication().getName());
assertEquals("sysowner", service.getApplication().getOwner());
assertEquals("N/A", service.getRegistry().getAddress());
assertEquals("dubbo", service.getProtocol().getName());
assertEquals(20819, service.getProtocol().getPort().intValue());
} finally {
providerContext.stop();
providerContext.close();
}
}
@SuppressWarnings("unchecked")
@Test
@Disabled("waiting-to-fix")
public void testSystemPropertyOverrideXml() throws Exception {
SysProps.setProperty("dubbo.application.name", "sysover");
SysProps.setProperty("dubbo.application.owner", "sysowner");
SysProps.setProperty("dubbo.registry.address", "N/A");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "20819");
SysProps.setProperty("dubbo.service.register", "false");
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/system-properties-override.xml");
try {
providerContext.start();
ServiceConfig<DemoService> service =
(ServiceConfig<DemoService>) providerContext.getBean("demoServiceConfig");
URL url = service.getExportedUrls().get(0);
assertEquals("sysover", url.getParameter("application"));
assertEquals("sysowner", url.getParameter("owner"));
assertEquals("dubbo", url.getProtocol());
assertEquals(20819, url.getPort());
String register = url.getParameter("register");
assertTrue(register != null && !"".equals(register));
assertEquals(false, Boolean.valueOf(register));
} finally {
providerContext.stop();
providerContext.close();
}
}
@Test
void testSystemPropertyOverrideReferenceConfig() throws Exception {
SysProps.setProperty("dubbo.reference.org.apache.dubbo.config.spring.api.DemoService.retries", "5");
SysProps.setProperty("dubbo.consumer.check", "false");
SysProps.setProperty("dubbo.consumer.timeout", "1234");
try {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
ProtocolConfig protocolConfig = new ProtocolConfig("injvm");
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setInterface(DemoService.class);
reference.setInjvm(true);
reference.setRetries(2);
DubboBootstrap.getInstance()
.application(new ApplicationConfig("testSystemPropertyOverrideReferenceConfig"))
.registry(new RegistryConfig(RegistryConfig.NO_AVAILABLE))
.protocol(protocolConfig)
.service(service)
.reference(reference)
.start();
// override retries
assertEquals(Integer.valueOf(5), reference.getRetries());
// set default value of check
assertEquals(false, reference.shouldCheck());
ModuleConfigManager moduleConfigManager =
ApplicationModel.defaultModel().getDefaultModule().getConfigManager();
ConsumerConfig defaultConsumer =
moduleConfigManager.getDefaultConsumer().get();
assertEquals(1234, defaultConsumer.getTimeout());
assertEquals(false, defaultConsumer.isCheck());
} finally {
// If we don't stop here, somewhere else will throw BeanCreationException of duplication.
DubboBootstrap.getInstance().stop();
}
}
@Test
@Disabled("waiting-to-fix")
public void testSystemPropertyOverrideApiDefault() throws Exception {
SysProps.setProperty("dubbo.application.name", "sysover");
SysProps.setProperty("dubbo.application.owner", "sysowner");
SysProps.setProperty("dubbo.registry.address", "N/A");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "20834");
try {
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<DemoService>();
serviceConfig.setInterface(DemoService.class);
serviceConfig.setRef(new DemoServiceImpl());
DubboBootstrap.getInstance().service(serviceConfig).start();
assertEquals("sysover", serviceConfig.getApplication().getName());
assertEquals("sysowner", serviceConfig.getApplication().getOwner());
assertEquals("N/A", serviceConfig.getRegistry().getAddress());
assertEquals("dubbo", serviceConfig.getProtocol().getName());
assertEquals(20834, serviceConfig.getProtocol().getPort().intValue());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
@Disabled("waiting-to-fix")
public void testSystemPropertyOverrideApi() throws Exception {
SysProps.setProperty("dubbo.application.name", "sysover");
SysProps.setProperty("dubbo.application.owner", "sysowner");
SysProps.setProperty("dubbo.registry.address", "N/A");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "20834");
try {
ApplicationConfig application = new ApplicationConfig();
application.setName("aaa");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("127.0.0.1");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("rmi");
protocol.setPort(1099);
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
DubboBootstrap.getInstance()
.application(application)
.registry(registry)
.protocol(protocol)
.service(service)
.start();
URL url = service.getExportedUrls().get(0);
assertEquals("sysover", url.getParameter("application"));
assertEquals("sysowner", url.getParameter("owner"));
assertEquals("dubbo", url.getProtocol());
assertEquals(20834, url.getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
@Disabled("waiting-to-fix")
public void testSystemPropertyOverrideProperties() throws Exception {
try {
int port = 1234;
SysProps.setProperty("dubbo.protocol.port", String.valueOf(port));
ApplicationConfig application = new ApplicationConfig();
application.setName("aaa");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("rmi");
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
DubboBootstrap.getInstance()
.application(application)
.registry(registry)
.protocol(protocol)
.service(service)
.start();
URL url = service.getExportedUrls().get(0);
// from api
assertEquals("aaa", url.getParameter("application"));
// from dubbo-binder.properties
assertEquals("world", url.getParameter("owner"));
// from system property
assertEquals(1234, url.getPort());
} finally {
System.clearProperty("dubbo.protocol.port");
DubboBootstrap.getInstance().stop();
}
}
@Test
@Disabled("waiting-to-fix")
@SuppressWarnings("unchecked")
public void testCustomizeParameter() throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(resourcePath + "/customize-parameter.xml");
try {
context.start();
ServiceBean<DemoService> serviceBean = (ServiceBean<DemoService>) context.getBean("demoServiceExport");
URL url = (URL) serviceBean.getExportedUrls().get(0);
assertEquals("protocol-paramA", url.getParameter("protocol.paramA"));
assertEquals("service-paramA", url.getParameter("service.paramA"));
} finally {
context.close();
}
}
@Test
@Disabled("waiting-to-fix")
public void testPath() throws Exception {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setPath("a/b$c");
try {
service.setPath("a?b");
fail();
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains(""));
}
}
@Test
@Disabled("waiting-to-fix")
public void testAnnotation() {
SimpleRegistryService registryService = new SimpleRegistryService();
Exporter<RegistryService> exporter = SimpleRegistryExporter.export(4548, registryService);
try {
SysProps.setProperty("provider.version", "1.2");
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext(resourcePath + "/annotation-provider.xml");
try {
providerContext.start();
ClassPathXmlApplicationContext consumerContext =
new ClassPathXmlApplicationContext(resourcePath + "/annotation-consumer.xml");
try {
consumerContext.start();
AnnotationAction annotationAction = (AnnotationAction) consumerContext.getBean("annotationAction");
String hello = annotationAction.doSayName("hello");
assertEquals("annotation:hello", hello);
} finally {
consumerContext.stop();
consumerContext.close();
}
} finally {
providerContext.stop();
providerContext.close();
}
} finally {
System.clearProperty("provider.version");
exporter.unexport();
}
}
@Test
void testDubboProtocolPortOverride() throws Exception {
int port = NetUtils.getAvailablePort();
SysProps.setProperty("dubbo.protocol.port", String.valueOf(port));
ServiceConfig<DemoService> service = null;
try {
ApplicationConfig application = new ApplicationConfig();
application.setName("dubbo-protocol-port-override");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
DubboBootstrap.getInstance()
.application(application)
.registry(registry)
.protocol(protocol)
.service(service)
.start();
assertEquals(port, service.getExportedUrls().get(0).getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
@Disabled("waiting-to-fix")
public void testProtocolRandomPort() throws Exception {
ServiceConfig<DemoService> demoService = null;
ServiceConfig<HelloService> helloService = null;
ApplicationConfig application = new ApplicationConfig();
application.setName("test-protocol-random-port");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("dubbo");
protocol.setPort(-1);
demoService = new ServiceConfig<DemoService>();
demoService.setInterface(DemoService.class);
demoService.setRef(new DemoServiceImpl());
demoService.setApplication(application);
demoService.setRegistry(registry);
demoService.setProtocol(protocol);
helloService = new ServiceConfig<HelloService>();
helloService.setInterface(HelloService.class);
helloService.setRef(new HelloServiceImpl());
helloService.setApplication(application);
helloService.setRegistry(registry);
helloService.setProtocol(protocol);
try {
DubboBootstrap.getInstance()
.application(application)
.registry(registry)
.protocol(protocol)
.service(demoService)
.service(helloService)
.start();
assertEquals(
demoService.getExportedUrls().get(0).getPort(),
helloService.getExportedUrls().get(0).getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
@Disabled("waiting-to-fix, see: https://github.com/apache/dubbo/pull/8534")
public void testReferGenericExport() throws Exception {
RegistryConfig rc = new RegistryConfig();
rc.setAddress(RegistryConfig.NO_AVAILABLE);
ServiceConfig<GenericService> sc = new ServiceConfig<GenericService>();
sc.setRegistry(rc);
sc.setInterface(DemoService.class.getName());
sc.setRef((method, parameterTypes, args) -> null);
ReferenceConfig<DemoService> ref = new ReferenceConfig<DemoService>();
ref.setRegistry(rc);
ref.setInterface(DemoService.class.getName());
try {
DubboBootstrap.getInstance()
.application(new ApplicationConfig("test-refer-generic-export"))
.service(sc)
.reference(ref)
.start();
fail();
} catch (Exception e) {
e.printStackTrace();
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testGenericServiceConfig() throws Exception {
ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
service.setRegistry(new RegistryConfig("mock://localhost"));
service.setInterface(DemoService.class.getName());
service.setGeneric(GENERIC_SERIALIZATION_BEAN);
service.setRef((method, parameterTypes, args) -> null);
try {
DubboBootstrap.getInstance()
.application(new ApplicationConfig("test"))
.service(service)
.start();
Collection<Registry> collection = MockRegistryFactory.getCachedRegistry();
MockRegistry registry = (MockRegistry) collection.iterator().next();
URL url = registry.getRegistered().get(0);
assertEquals(GENERIC_SERIALIZATION_BEAN, url.getParameter(GENERIC_KEY));
} finally {
MockRegistryFactory.cleanCachedRegistry();
DubboBootstrap.getInstance().stop();
}
}
@Test
void testGenericServiceConfigThroughSpring() throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/generic-export.xml");
try {
ctx.start();
ServiceConfig serviceConfig = (ServiceConfig) ctx.getBean("dubboDemoService");
URL url = (URL) serviceConfig.getExportedUrls().get(0);
assertEquals(GENERIC_SERIALIZATION_BEAN, url.getParameter(GENERIC_KEY));
} finally {
ctx.close();
}
}
}
| 8,623 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/AbstractRegistryService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.RegistryService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_NOTIFY_EVENT;
/**
* AbstractRegistryService
*/
public abstract class AbstractRegistryService implements RegistryService {
// logger
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
// registered services
// Map<serviceName, Map<url, queryString>>
private final ConcurrentMap<String, List<URL>> registered = new ConcurrentHashMap<String, List<URL>>();
// subscribed services
// Map<serviceName, queryString>
private final ConcurrentMap<String, Map<String, String>> subscribed =
new ConcurrentHashMap<String, Map<String, String>>();
// notified services
// Map<serviceName, Map<url, queryString>>
private final ConcurrentMap<String, List<URL>> notified = new ConcurrentHashMap<String, List<URL>>();
// notification listeners for the subscribed services
// Map<serviceName, List<notificationListener>>
private final ConcurrentMap<String, List<NotifyListener>> notifyListeners =
new ConcurrentHashMap<String, List<NotifyListener>>();
@Override
public void register(URL url) {
if (logger.isInfoEnabled()) {
logger.info("Register service: " + url.getServiceKey() + ",url:" + url);
}
register(url.getServiceKey(), url);
}
@Override
public void unregister(URL url) {
if (logger.isInfoEnabled()) {
logger.info("Unregister service: " + url.getServiceKey() + ",url:" + url);
}
unregister(url.getServiceKey(), url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
if (logger.isInfoEnabled()) {
logger.info("Subscribe service: " + url.getServiceKey() + ",url:" + url);
}
subscribe(url.getServiceKey(), url, listener);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
if (logger.isInfoEnabled()) {
logger.info("Unsubscribe service: " + url.getServiceKey() + ",url:" + url);
}
unsubscribe(url.getServiceKey(), url, listener);
}
@Override
public List<URL> lookup(URL url) {
return getRegistered(url.getServiceKey());
}
public void register(String service, URL url) {
if (service == null) {
throw new IllegalArgumentException("service == null");
}
if (url == null) {
throw new IllegalArgumentException("url == null");
}
List<URL> urls = ConcurrentHashMapUtils.computeIfAbsent(registered, service, k -> new CopyOnWriteArrayList<>());
if (!urls.contains(url)) {
urls.add(url);
}
}
public void unregister(String service, URL url) {
if (service == null) {
throw new IllegalArgumentException("service == null");
}
if (url == null) {
throw new IllegalArgumentException("url == null");
}
List<URL> urls = registered.get(service);
if (urls != null) {
URL deleteURL = null;
for (URL u : urls) {
if (u.toIdentityString().equals(url.toIdentityString())) {
deleteURL = u;
break;
}
}
if (deleteURL != null) {
urls.remove(deleteURL);
}
}
}
public void subscribe(String service, URL url, NotifyListener listener) {
if (service == null) {
throw new IllegalArgumentException("service == null");
}
if (url == null) {
throw new IllegalArgumentException("parameters == null");
}
if (listener == null) {
throw new IllegalArgumentException("listener == null");
}
subscribed.put(service, url.getParameters());
addListener(service, listener);
}
public void unsubscribe(String service, URL url, NotifyListener listener) {
if (service == null) {
throw new IllegalArgumentException("service == null");
}
if (url == null) {
throw new IllegalArgumentException("parameters == null");
}
if (listener == null) {
throw new IllegalArgumentException("listener == null");
}
subscribed.remove(service);
removeListener(service, listener);
}
private void addListener(final String service, final NotifyListener listener) {
if (listener == null) {
return;
}
List<NotifyListener> listeners =
ConcurrentHashMapUtils.computeIfAbsent(notifyListeners, service, k -> new CopyOnWriteArrayList<>());
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
private void removeListener(final String service, final NotifyListener listener) {
if (listener == null) {
return;
}
List<NotifyListener> listeners = notifyListeners.get(service);
if (listeners != null) {
listeners.remove(listener);
}
}
private void doNotify(String service, List<URL> urls) {
notified.put(service, urls);
List<NotifyListener> listeners = notifyListeners.get(service);
if (listeners != null) {
for (NotifyListener listener : listeners) {
try {
notify(service, urls, listener);
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_NOTIFY_EVENT,
"",
"",
"Failed to notify registry event, service: " + service + ", urls: " + urls + ", cause: "
+ t.getMessage(),
t);
}
}
}
}
protected void notify(String service, List<URL> urls, NotifyListener listener) {
listener.notify(urls);
}
protected final void forbid(String service) {
doNotify(service, new ArrayList<URL>(0));
}
protected final void notify(String service, List<URL> urls) {
if (StringUtils.isEmpty(service) || CollectionUtils.isEmpty(urls)) {
return;
}
doNotify(service, urls);
}
public Map<String, List<URL>> getRegistered() {
return Collections.unmodifiableMap(registered);
}
public List<URL> getRegistered(String service) {
return Collections.unmodifiableList(registered.get(service));
}
public Map<String, Map<String, String>> getSubscribed() {
return Collections.unmodifiableMap(subscribed);
}
public Map<String, String> getSubscribed(String service) {
return subscribed.get(service);
}
public Map<String, List<URL>> getNotified() {
return Collections.unmodifiableMap(notified);
}
public List<URL> getNotified(String service) {
return Collections.unmodifiableList(notified.get(service));
}
public Map<String, List<NotifyListener>> getListeners() {
return Collections.unmodifiableMap(notifyListeners);
}
}
| 8,624 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SysProps.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Use to set and clear System property
*/
public class SysProps {
private static Map<String, String> map = new LinkedHashMap<String, String>();
public static void reset() {
map.clear();
}
public static void setProperty(String key, String value) {
map.put(key, value);
System.setProperty(key, value);
}
public static void clear() {
for (String key : map.keySet()) {
System.clearProperty(key);
}
reset();
}
}
| 8,625 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/GenericDemoService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
public class GenericDemoService implements GenericService {
public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
return null;
}
}
| 8,626 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/SimpleRegistryExporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import java.io.IOException;
import java.net.ServerSocket;
import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY;
/**
* SimpleRegistryExporter
*/
public class SimpleRegistryExporter {
private static final Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
private static final ProxyFactory PROXY_FACTORY =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
public static synchronized Exporter<RegistryService> exportIfAbsent(int port) {
try {
new ServerSocket(port).close();
return export(port);
} catch (IOException e) {
return null;
}
}
public static Exporter<RegistryService> export(int port) {
return export(port, new SimpleRegistryService());
}
public static Exporter<RegistryService> export(int port, RegistryService registryService) {
return protocol.export(PROXY_FACTORY.getInvoker(
registryService,
RegistryService.class,
new URLBuilder(DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName())
.setPath(RegistryService.class.getName())
.addParameter(INTERFACE_KEY, RegistryService.class.getName())
.addParameter(CLUSTER_STICKY_KEY, "true")
.addParameter(CALLBACK_INSTANCES_LIMIT_KEY, "1000")
.addParameter("ondisconnect", "disconnect")
.addParameter("subscribe.1.callback", "true")
.addParameter("unsubscribe.1.callback", "false")
.build()));
}
}
| 8,627 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/UnserializableBoxDemoServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
/**
* DemoServiceImpl
*/
public class UnserializableBoxDemoServiceImpl implements DemoService {
public String sayName(String name) {
return "say:" + name;
}
public Box getBox() {
return new UnserializableBox();
}
}
| 8,628 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/MethodCallbackImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.MethodCallback;
import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class MethodCallbackImpl implements MethodCallback {
private String onInvoke1 = "";
private final Object lock = new Object();
private String onReturn1 = "";
private String onThrow1 = "";
private String onInvoke2 = "";
private String onReturn2 = "";
private String onThrow2 = "";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
public static AtomicInteger cnt = new AtomicInteger();
@PostConstruct
protected void init() {
checkInjection();
}
@Transactional(rollbackFor = Exception.class)
@Override
public void oninvoke1(String request) {
try {
checkInjection();
checkTranscation();
synchronized (lock) {
this.onInvoke1 += "dubbo invoke success!";
}
} catch (Exception e) {
synchronized (lock) {
this.onInvoke1 += e.toString();
}
throw e;
}
}
@Transactional(rollbackFor = Exception.class)
@Override
public void oninvoke2(String request) {
try {
checkInjection();
checkTranscation();
synchronized (lock) {
this.onInvoke2 += "dubbo invoke success(2)!";
}
} catch (Exception e) {
synchronized (lock) {
this.onInvoke2 += e.toString();
}
throw e;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void onreturn1(String response, String request) {
try {
checkInjection();
checkTranscation();
synchronized (lock) {
this.onReturn1 += "dubbo return success!";
}
} catch (Exception e) {
synchronized (lock) {
this.onReturn1 += e.toString();
}
throw e;
} finally {
cnt.incrementAndGet();
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void onreturn2(String response, String request) {
try {
checkInjection();
checkTranscation();
synchronized (lock) {
this.onReturn2 += "dubbo return success(2)!";
}
} catch (Exception e) {
synchronized (lock) {
this.onReturn2 += e.toString();
}
throw e;
} finally {
cnt.incrementAndGet();
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void onthrow1(Throwable ex, String request) {
try {
checkInjection();
checkTranscation();
synchronized (lock) {
this.onThrow1 += "dubbo throw exception!";
}
} catch (Exception e) {
synchronized (lock) {
this.onThrow1 += e.toString();
}
throw e;
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void onthrow2(Throwable ex, String request) {
try {
checkInjection();
checkTranscation();
synchronized (lock) {
this.onThrow2 += "dubbo throw exception(2)!";
}
} catch (Exception e) {
synchronized (lock) {
this.onThrow2 += e.toString();
}
throw e;
}
}
public String getOnInvoke1() {
return this.onInvoke1;
}
public String getOnReturn1() {
return this.onReturn1;
}
public String getOnThrow1() {
return this.onThrow1;
}
public String getOnInvoke2() {
return this.onInvoke2;
}
public String getOnReturn2() {
return this.onReturn2;
}
public String getOnThrow2() {
return this.onThrow2;
}
private void checkInjection() {
if (environment == null) {
throw new IllegalStateException("environment is null");
}
if (context == null) {
throw new IllegalStateException("application context is null");
}
}
private void checkTranscation() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("No active transaction");
}
}
}
| 8,629 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/HelloServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.HelloService;
public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
return "Hello, " + name;
}
}
| 8,630 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/NotifyService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
public class NotifyService {
public void onInvoke(Object[] params) {
System.out.println("invoke param-0: " + params[0]);
}
public void onReturn(Object result, Object[] params) {
System.out.println("invoke param-0: " + params[0] + ", return: " + result);
}
public void onThrow(Throwable t, Object[] params) {
System.out.println("invoke param-0: " + params[0] + ", throw: " + t.getMessage());
}
}
| 8,631 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
/**
* DemoServiceImpl
*/
public class DemoServiceImpl implements DemoService {
private String prefix = "say:";
public String sayName(String name) {
return prefix + name;
}
public Box getBox() {
return null;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
| 8,632 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceImpl_LongWaiting.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
/**
* DemoServiceImpl
*/
public class DemoServiceImpl_LongWaiting implements DemoService {
public String sayName(String name) {
try {
Thread.sleep(100 * 1000);
} catch (InterruptedException e) {
}
return "say:" + name;
}
public Box getBox() {
return null;
}
}
| 8,633 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/UnserializableBox.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.Box;
public class UnserializableBox implements Box {
private static final long serialVersionUID = -4141012025649711421L;
private int count = 3;
private String name = "Jerry";
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Box [count=" + count + ", name=" + name + "]";
}
}
| 8,634 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/impl/DemoServiceSonImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.impl;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoServiceSon;
public class DemoServiceSonImpl implements DemoServiceSon {
private String prefix = "say:";
public String sayName(String name) {
return prefix + name;
}
public Box getBox() {
return null;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
| 8,635 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/metrics/SpringBootConfigMetricsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.metrics;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
@SpringBootTest(
properties = {
"dubbo.application.NAME = dubbo-demo-application",
"dubbo.module.name = dubbo-demo-module",
"dubbo.registry.address = zookeeper://localhost:2181",
"dubbo.protocol.name=dubbo",
"dubbo.protocol.port=20880",
"dubbo.metrics.protocol=prometheus",
"dubbo.metrics.export-service-protocol=tri",
"dubbo.metrics.export-service-port=9999",
"dubbo.metrics.enable-jvm=true",
"dubbo.metrics.prometheus.exporter.enabled=true",
"dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true",
"dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080",
"dubbo.metrics.aggregation.enabled=true",
"dubbo.metrics.aggregation.bucket-num=5",
"dubbo.metrics.aggregation.time-window-seconds=120",
"dubbo.metrics.histogram.enabled=true",
"dubbo.metadata-report.address=${zookeeper.connection.address.2}"
},
classes = {SpringBootConfigMetricsTest.class})
@Configuration
@ComponentScan
@EnableDubbo
public class SpringBootConfigMetricsTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private ConfigManager configManager;
@Test
public void testMetrics() {
MetricsConfig metricsConfig = configManager.getMetrics().get();
Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol());
Assertions.assertTrue(metricsConfig.getEnableJvm());
Assertions.assertEquals("tri", metricsConfig.getExportServiceProtocol());
Assertions.assertEquals(9999, metricsConfig.getExportServicePort());
Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnabled());
Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnableHttpServiceDiscovery());
Assertions.assertEquals(
"localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl());
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
}
}
| 8,636 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context;
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.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.DubboStateListener;
import org.apache.dubbo.config.spring.SysProps;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class KeepRunningOnSpringClosedTest {
@Test
void test() {
// set KeepRunningOnSpringClosed flag for next spring context
DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {
context.setKeepRunningOnSpringClosed(true);
});
ClassPathXmlApplicationContext providerContext = null;
try {
String resourcePath = "org/apache/dubbo/config/spring";
providerContext = new ClassPathXmlApplicationContext(
resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml");
providerContext.start();
// Expect 1: dubbo application state is STARTED after spring context start finish.
// No need check and wait
DubboStateListener dubboStateListener = providerContext.getBean(DubboStateListener.class);
Assertions.assertEquals(DeployState.STARTED, dubboStateListener.getState());
ModuleModel moduleModel = providerContext.getBean(ModuleModel.class);
ModuleDeployer moduleDeployer = moduleModel.getDeployer();
Assertions.assertTrue(moduleDeployer.isStarted());
ApplicationDeployer applicationDeployer =
moduleModel.getApplicationModel().getDeployer();
Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState());
Assertions.assertEquals(true, applicationDeployer.isStarted());
Assertions.assertEquals(false, applicationDeployer.isStopped());
Assertions.assertNotNull(DubboSpringInitializer.findBySpringContext(providerContext));
// close spring context
providerContext.close();
// Expect 2: dubbo application will not be destroyed after closing spring context cause
// setKeepRunningOnSpringClosed(true)
Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState());
Assertions.assertEquals(true, applicationDeployer.isStarted());
Assertions.assertEquals(false, applicationDeployer.isStopped());
Assertions.assertNull(DubboSpringInitializer.findBySpringContext(providerContext));
} finally {
DubboBootstrap.getInstance().stop();
SysProps.clear();
if (providerContext != null) {
providerContext.close();
}
}
}
}
| 8,637 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationTestConfiguration;
import org.apache.dubbo.config.spring.context.annotation.consumer.test.TestConsumerConfiguration;
import org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
/**
* {@link EnableDubbo} Test
*
* @since 2.5.8
*/
class EnableDubboTest {
private AnnotationConfigApplicationContext context;
@BeforeEach
public void setUp() {
context = new AnnotationConfigApplicationContext();
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
context.close();
DubboBootstrap.reset();
}
@Test
void testProvider() {
context.register(TestProviderConfiguration.class);
context.refresh();
DemoService demoService = context.getBean(DemoService.class);
String value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
Class<?> beanClass = AopUtils.getTargetClass(demoService);
// DemoServiceImpl with @Transactional
Assertions.assertEquals(DemoServiceImpl.class, beanClass);
// Test @Transactional is present or not
Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class));
}
@Test
void testConsumer() {
context.register(TestProviderConfiguration.class, TestConsumerConfiguration.class);
context.refresh();
TestConsumerConfiguration consumerConfiguration = context.getBean(TestConsumerConfiguration.class);
DemoService demoService = consumerConfiguration.getDemoService();
String value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
DemoService autowiredDemoService = consumerConfiguration.getAutowiredDemoService();
Assertions.assertEquals("Hello,Mercy", autowiredDemoService.sayName("Mercy"));
DemoService autowiredReferDemoService = consumerConfiguration.getAutowiredReferDemoService();
Assertions.assertEquals("Hello,Mercy", autowiredReferDemoService.sayName("Mercy"));
TestConsumerConfiguration.Child child = context.getBean(TestConsumerConfiguration.Child.class);
// From Child
demoService = child.getDemoServiceFromChild();
Assertions.assertNotNull(demoService);
value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
// From Parent
// demoService = child.getDemoServiceFromParent();
//
// Assertions.assertNotNull(demoService);
//
// value = demoService.sayName("Mercy");
//
// Assertions.assertEquals("Hello,Mercy", value);
// From Ancestor
demoService = child.getDemoServiceFromAncestor();
Assertions.assertNotNull(demoService);
value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
// Test my-registry2 bean presentation
RegistryConfig registryConfig = context.getBean("my-registry", RegistryConfig.class);
// Test multiple binding
Assertions.assertEquals("N/A", registryConfig.getAddress());
}
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider")
@ComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider")
@PropertySource("classpath:/META-INF/dubbo-provider.properties")
@Import(ServiceAnnotationTestConfiguration.class)
@EnableTransactionManagement
public static class TestProviderConfiguration {
@Primary
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new PlatformTransactionManager() {
@Override
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
return null;
}
@Override
public void commit(TransactionStatus status) throws TransactionException {}
@Override
public void rollback(TransactionStatus status) throws TransactionException {}
};
}
}
}
| 8,638 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.consumer.ConsumerConfiguration;
import org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl;
import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
/**
* {@link DubboComponentScanRegistrar} Test
*
* @since 2.5.8
*/
class DubboComponentScanRegistrarTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {}
@Test
void test() {
AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext();
providerContext.register(ProviderConfiguration.class);
providerContext.refresh();
DemoService demoService = providerContext.getBean(DemoService.class);
String value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
Class<?> beanClass = AopUtils.getTargetClass(demoService);
// DemoServiceImpl with @Transactional
Assertions.assertEquals(DemoServiceImpl.class, beanClass);
// Test @Transactional is present or not
Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class));
// consumer app
AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext();
consumerContext.register(ConsumerConfiguration.class);
consumerContext.refresh();
ConsumerConfiguration consumerConfiguration = consumerContext.getBean(ConsumerConfiguration.class);
demoService = consumerConfiguration.getDemoService();
value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
ConsumerConfiguration.Child child = consumerContext.getBean(ConsumerConfiguration.Child.class);
// From Child
demoService = child.getDemoServiceFromChild();
Assertions.assertNotNull(demoService);
value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
// From Parent
demoService = child.getDemoServiceFromParent();
Assertions.assertNotNull(demoService);
value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
// From Ancestor
demoService = child.getDemoServiceFromAncestor();
Assertions.assertNotNull(demoService);
value = demoService.sayName("Mercy");
Assertions.assertEquals("Hello,Mercy", value);
providerContext.close();
consumerContext.close();
}
}
| 8,639 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.PropertySource;
import static com.alibaba.spring.util.BeanRegistrar.hasAlias;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* {@link EnableDubboConfig} Test
*
* @since 2.5.8
*/
class EnableDubboConfigTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
DubboBootstrap.reset();
}
// @Test
public void testSingle() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(TestConfig.class);
context.refresh();
// application
ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.class);
Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName());
// module
ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.class);
Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName());
// registry
RegistryConfig registryConfig = context.getBean(RegistryConfig.class);
Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
// protocol
ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class);
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(Integer.valueOf(20880), protocolConfig.getPort());
// monitor
MonitorConfig monitorConfig = context.getBean(MonitorConfig.class);
Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress());
// provider
ProviderConfig providerConfig = context.getBean(ProviderConfig.class);
Assertions.assertEquals("127.0.0.1", providerConfig.getHost());
// consumer
ConsumerConfig consumerConfig = context.getBean(ConsumerConfig.class);
Assertions.assertEquals("netty", consumerConfig.getClient());
// asserts aliases
assertFalse(hasAlias(context, "org.apache.dubbo.config.RegistryConfig#0", "zookeeper"));
assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper"));
}
// @Test
public void testMultiple() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(TestMultipleConfig.class);
context.refresh();
RegistryConfig registry1 = context.getBean("registry1", RegistryConfig.class);
Assertions.assertEquals(2181, registry1.getPort());
RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class);
Assertions.assertEquals(2182, registry2.getPort());
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
Collection<ProtocolConfig> protocolConfigs = configManager.getProtocols();
Assertions.assertEquals(3, protocolConfigs.size());
configManager.getProtocol("dubbo").get();
configManager.getProtocol("rest").get();
configManager.getProtocol("thrift").get();
// asserts aliases
// assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2"));
// assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3"));
}
@EnableDubboConfig
@PropertySource("META-INF/config.properties")
private static class TestMultipleConfig {}
@EnableDubboConfig(multiple = false)
@PropertySource("META-INF/config.properties")
private static class TestConfig {}
}
| 8,640 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.support.ResourcePropertySource;
/**
* {@link DubboConfigConfiguration} Test
*
* @since 2.5.8
*/
class DubboConfigConfigurationTest {
private AnnotationConfigApplicationContext context;
@BeforeEach
public void before() throws IOException {
DubboBootstrap.reset();
context = new AnnotationConfigApplicationContext();
ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties");
context.getEnvironment().getPropertySources().addFirst(propertySource);
}
@AfterEach
public void after() {
context.close();
}
@Test
void testSingle() throws IOException {
context.register(DubboConfigConfiguration.Single.class);
context.refresh();
// application
ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.class);
Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName());
// module
ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.class);
Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName());
// registry
RegistryConfig registryConfig = context.getBean(RegistryConfig.class);
Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
// protocol
ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class);
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(Integer.valueOf(20880), protocolConfig.getPort());
}
@Test
void testMultiple() {
context.register(DubboConfigConfiguration.Multiple.class);
context.refresh();
RegistryConfig registry1 = context.getBean("registry1", RegistryConfig.class);
Assertions.assertEquals(2181, registry1.getPort());
RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class);
Assertions.assertEquals(2182, registry2.getPort());
}
}
| 8,641 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation.provider;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.stereotype.Service;
/**
* Default {@link HelloService} annotation with Spring's {@link Service}
* and Dubbo's {@link org.apache.dubbo.config.annotation.Service}
*
*/
@Service
@DubboService
public class DefaultHelloService implements HelloService {
@Override
public String sayHello(String name) {
return "Greeting, " + name;
}
}
| 8,642 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation.provider;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.api.HelloService;
/**
* {@link HelloService} Implementation just annotating Dubbo's {@link Service}
*
* @since 2.5.9
*/
@Service(interfaceName = "org.apache.dubbo.config.spring.api.HelloService", version = "2")
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
| 8,643 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation.provider;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* {@link DemoService} Service implementation
*
* @since 2.5.8
*/
@org.apache.dubbo.config.annotation.Service(
version = "2.5.7",
application = "${demo.service.application}",
protocol = "${demo.service.protocol}",
registry = "${demo.service.registry}",
methods = @Method(timeout = 100, name = "sayName"))
@Service
@Transactional
public class DemoServiceImpl implements DemoService {
@Override
public String sayName(String name) {
return "Hello," + name;
}
@Override
public Box getBox() {
throw new UnsupportedOperationException("For Purposes!");
}
}
| 8,644 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation.provider;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.AbstractPlatformTransactionManager;
import org.springframework.transaction.support.DefaultTransactionStatus;
@DubboComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider")
@PropertySource("classpath:/META-INF/default.properties")
@EnableTransactionManagement
public class ProviderConfiguration {
/**
* Current application configuration, to replace XML config:
* <prev>
* <dubbo:application name="dubbo-demo-application"/>
* </prev>
*
* @return {@link ApplicationConfig} Bean
*/
@Bean("dubbo-demo-application")
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo-demo-application");
return applicationConfig;
}
/**
* Current registry center configuration, to replace XML config:
* <prev>
* <dubbo:registry id="my-registry" address="N/A"/>
* </prev>
*
* @return {@link RegistryConfig} Bean
*/
@Bean("my-registry")
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
return registryConfig;
}
/**
* Current protocol configuration, to replace XML config:
* <prev>
* <dubbo:protocol name="dubbo" port="12345"/>
* </prev>
*
* @return {@link ProtocolConfig} Bean
*/
@Bean("dubbo")
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(12345);
return protocolConfig;
}
@Primary
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new AbstractPlatformTransactionManager() {
private Logger logger = LoggerFactory.getLogger("TestPlatformTransactionManager");
@Override
protected Object doGetTransaction() throws TransactionException {
String transaction = "transaction_" + UUID.randomUUID().toString();
logger.info("Create transaction: " + transaction);
return transaction;
}
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
logger.info("Begin transaction: " + transaction);
}
@Override
protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
logger.info("Commit transaction: " + status.getTransaction());
}
@Override
protected void doRollback(DefaultTransactionStatus status) throws TransactionException {
logger.info("Rollback transaction: " + status.getTransaction());
}
};
}
}
| 8,645 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation.consumer;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration("consumerConfiguration")
@DubboComponentScan(basePackageClasses = ConsumerConfiguration.class)
@PropertySource("META-INF/default.properties")
public class ConsumerConfiguration {
private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7";
/**
* Current application configuration, to replace XML config:
* <prev>
* <dubbo:application name="dubbo-demo-application"/>
* </prev>
*
* @return {@link ApplicationConfig} Bean
*/
@Bean("dubbo-demo-application")
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo-demo-application");
return applicationConfig;
}
/**
* Current registry center configuration, to replace XML config:
* <prev>
* <dubbo:registry address="N/A"/>
* </prev>
*
* @return {@link RegistryConfig} Bean
*/
@Bean
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
return registryConfig;
}
@Autowired
private DemoService demoServiceFromAncestor;
@Reference(version = "2.5.7", url = remoteURL)
private DemoService demoService;
public DemoService getDemoService() {
return demoService;
}
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
@Bean
public Child c() {
return new Child();
}
public abstract static class Ancestor {
@Reference(version = "2.5.7", url = remoteURL)
private DemoService demoServiceFromAncestor;
public DemoService getDemoServiceFromAncestor() {
return demoServiceFromAncestor;
}
public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) {
this.demoServiceFromAncestor = demoServiceFromAncestor;
}
}
public abstract static class Parent extends Ancestor {
private DemoService demoServiceFromParent;
public DemoService getDemoServiceFromParent() {
return demoServiceFromParent;
}
@Reference(version = "2.5.7", url = remoteURL)
public void setDemoServiceFromParent(DemoService demoServiceFromParent) {
this.demoServiceFromParent = demoServiceFromParent;
}
}
public static class Child extends Parent {
@Autowired
private DemoService demoService;
@Reference(version = "2.5.7", url = remoteURL)
private DemoService demoServiceFromChild;
public DemoService getDemoService() {
return demoService;
}
public DemoService getDemoServiceFromChild() {
return demoServiceFromChild;
}
public void setDemoServiceFromChild(DemoService demoServiceFromChild) {
this.demoServiceFromChild = demoServiceFromChild;
}
}
}
| 8,646 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.annotation.consumer.test;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Test Consumer Configuration
*
* @since 2.5.7
*/
@EnableDubbo(scanBasePackageClasses = TestConsumerConfiguration.class)
@PropertySource("classpath:/META-INF/dubbb-consumer.properties")
@EnableTransactionManagement
public class TestConsumerConfiguration {
private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7";
@Reference(
id = "demoService",
version = "2.5.7",
url = remoteURL,
application = "dubbo-demo-application",
filter = "mymock")
private DemoService demoService;
@Autowired
@Qualifier("demoServiceImpl")
private DemoService autowiredDemoService;
@Autowired
@Qualifier("demoService")
private DemoService autowiredReferDemoService;
public DemoService getAutowiredDemoService() {
return autowiredDemoService;
}
public DemoService getAutowiredReferDemoService() {
return autowiredReferDemoService;
}
public DemoService getDemoService() {
return demoService;
}
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
@Bean
public Child c() {
return new Child();
}
public abstract static class Ancestor {
@DubboReference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application")
private DemoService demoServiceFromAncestor;
public DemoService getDemoServiceFromAncestor() {
return demoServiceFromAncestor;
}
public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) {
this.demoServiceFromAncestor = demoServiceFromAncestor;
}
}
public static class Child extends Ancestor {
@Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application")
private DemoService demoServiceFromChild;
public DemoService getDemoServiceFromChild() {
return demoServiceFromChild;
}
public void setDemoServiceFromChild(DemoService demoServiceFromChild) {
this.demoServiceFromChild = demoServiceFromChild;
}
}
}
| 8,647 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.properties;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@ExtendWith(SpringExtension.class)
@TestPropertySource(locations = "classpath:/dubbo-binder.properties")
@ContextConfiguration(classes = DefaultDubboConfigBinder.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
class DefaultDubboConfigBinderTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@Autowired
private DubboConfigBinder dubboConfigBinder;
@Test
void testBinder() {
ApplicationConfig applicationConfig = new ApplicationConfig();
dubboConfigBinder.bind("dubbo.application", applicationConfig);
Assertions.assertEquals("hello", applicationConfig.getName());
Assertions.assertEquals("world", applicationConfig.getOwner());
RegistryConfig registryConfig = new RegistryConfig();
dubboConfigBinder.bind("dubbo.registry", registryConfig);
Assertions.assertEquals("10.20.153.17", registryConfig.getAddress());
ProtocolConfig protocolConfig = new ProtocolConfig();
dubboConfigBinder.bind("dubbo.protocol", protocolConfig);
Assertions.assertEquals(Integer.valueOf(20881), protocolConfig.getPort());
}
}
| 8,648 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.context.customize;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.SysProps;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.DubboSpringInitCustomizerHolder;
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.ServiceDescriptor;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class DubboSpringInitCustomizerTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
SysProps.setProperty("dubbo.registry.address", ZookeeperRegistryCenterConfig.getConnectionAddress());
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
SysProps.clear();
}
@Test
void testReloadSpringContext() {
ClassPathXmlApplicationContext providerContext1 = null;
ClassPathXmlApplicationContext providerContext2 = null;
ApplicationModel applicationModel = new FrameworkModel().newApplication();
applicationModel.getDefaultModule();
try {
// start spring context 1
ModuleModel moduleModel1 = applicationModel.newModule();
DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {
context.setModuleModel(moduleModel1);
});
providerContext1 = new ClassPathXmlApplicationContext("dubbo-provider-v1.xml", getClass());
ModuleModel moduleModelFromSpring1 = providerContext1.getBean(ModuleModel.class);
Assertions.assertSame(moduleModel1, moduleModelFromSpring1);
String serviceKey1 = HelloService.class.getName() + ":1.0.0";
ServiceDescriptor serviceDescriptor1 =
moduleModelFromSpring1.getServiceRepository().lookupService(serviceKey1);
Assertions.assertNotNull(serviceDescriptor1);
// close spring context 1
providerContext1.close();
Assertions.assertTrue(moduleModel1.isDestroyed());
Assertions.assertFalse(moduleModel1.getApplicationModel().isDestroyed());
providerContext1 = null;
ModuleModel moduleModel2 = applicationModel.newModule();
DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {
context.setModuleModel(moduleModel2);
});
// load spring context 2
providerContext2 = new ClassPathXmlApplicationContext("dubbo-provider-v2.xml", getClass());
ModuleModel moduleModelFromSpring2 = providerContext2.getBean(ModuleModel.class);
Assertions.assertSame(moduleModel2, moduleModelFromSpring2);
Assertions.assertNotSame(moduleModelFromSpring1, moduleModelFromSpring2);
String serviceKey2 = HelloService.class.getName() + ":2.0.0";
ServiceDescriptor serviceDescriptor2 =
moduleModelFromSpring2.getServiceRepository().lookupService(serviceKey2);
Assertions.assertNotNull(serviceDescriptor2);
Assertions.assertNotSame(serviceDescriptor1, serviceDescriptor2);
providerContext2.close();
providerContext2 = null;
} finally {
if (providerContext1 != null) {
providerContext1.close();
}
if (providerContext2 != null) {
providerContext2.close();
}
applicationModel.destroy();
}
}
}
| 8,649 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/BeanForContext2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.extension;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanForContext2 {
@Bean("bean1")
public DemoService context2Bean() {
return new DemoServiceImpl();
}
}
| 8,650 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjectorTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.extension;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.config.spring.impl.HelloServiceImpl;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.Protocol;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@EnableDubbo(scanBasePackages = "")
@Configuration
class SpringExtensionInjectorTest {
@BeforeEach
public void init() {
DubboBootstrap.reset();
}
@AfterEach
public void destroy() {}
@Test
void testSpringInjector() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
try {
context.setDisplayName("Context1");
context.register(getClass());
context.refresh();
SpringExtensionInjector springExtensionInjector =
SpringExtensionInjector.get(DubboBeanUtils.getApplicationModel(context));
Assertions.assertEquals(springExtensionInjector.getContext(), context);
Protocol protocol = springExtensionInjector.getInstance(Protocol.class, "protocol");
Assertions.assertNull(protocol);
DemoService demoServiceBean1 = springExtensionInjector.getInstance(DemoService.class, "bean1");
Assertions.assertNotNull(demoServiceBean1);
DemoService demoServiceBean2 = springExtensionInjector.getInstance(DemoService.class, "bean2");
Assertions.assertNotNull(demoServiceBean2);
HelloService helloServiceBean = springExtensionInjector.getInstance(HelloService.class, "hello");
Assertions.assertNotNull(helloServiceBean);
HelloService helloService = springExtensionInjector.getInstance(HelloService.class, null);
Assertions.assertEquals(helloService, helloServiceBean);
Assertions.assertThrows(
IllegalStateException.class,
() -> springExtensionInjector.getInstance(DemoService.class, null),
"Expect single but found 2 beans in spring context: [bean1, bean2]");
} finally {
context.close();
}
}
@Bean("bean1")
public DemoService bean1() {
return new DemoServiceImpl();
}
@Bean("bean2")
public DemoService bean2() {
return new DemoServiceImpl();
}
@Bean("hello")
public HelloService helloService() {
return new HelloServiceImpl();
}
@Bean
public ApplicationConfig applicationConfig() {
return new ApplicationConfig("test-app");
}
}
| 8,651 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.conditional1;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.annotation.Order;
/**
* issue: https://github.com/apache/dubbo-spring-boot-project/issues/779
*/
@SpringBootTest(
properties = {"dubbo.registry.address=N/A"},
classes = {XmlReferenceBeanConditionalTest.class})
@Configuration
// @ComponentScan
class XmlReferenceBeanConditionalTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
void testConsumer() {
Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloService"));
Assertions.assertNull(helloServiceMap.get("myHelloService"));
}
@Order(Integer.MAX_VALUE - 2)
@Configuration
@ImportResource("classpath:/org/apache/dubbo/config/spring/boot/conditional1/consumer/dubbo-consumer.xml")
public static class ConsumerConfiguration {}
@Order(Integer.MAX_VALUE - 1)
@Configuration
public static class ConsumerConfiguration2 {
// TEST Conditional, this bean should be ignored
@Bean
@ConditionalOnMissingBean
public HelloService myHelloService() {
return new HelloService() {
@Override
public String sayHello(String name) {
return "HI, " + name;
}
};
}
}
}
| 8,652 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.importxml;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@SpringBootTest(
properties = {"dubbo.registry.protocol=zookeeper", "dubbo.registry.address=localhost:2181"},
classes = {SpringBootImportDubboXmlTest.class})
@Configuration
@ComponentScan
@ImportResource("classpath:/org/apache/dubbo/config/spring/boot/importxml/consumer/dubbo-consumer.xml")
class SpringBootImportDubboXmlTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Test
void testConsumer() {
try {
helloService.sayHello("dubbo");
Assertions.fail("Should not be called successfully");
} catch (Exception e) {
String s = e.toString();
Assertions.assertTrue(s.contains("No provider available"), s);
Assertions.assertTrue(s.contains("service org.apache.dubbo.config.spring.api.HelloService"), s);
}
}
}
| 8,653 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.conditional4;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* issue: https://github.com/apache/dubbo-spring-boot-project/issues/779
*/
@SpringBootTest(
properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"},
classes = {JavaConfigReferenceBeanConditionalTest4.class})
@Configuration
// @ComponentScan
@EnableDubbo
public class JavaConfigReferenceBeanConditionalTest4 {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testConsumer() {
Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNull(helloServiceMap.get("helloService"));
HelloService helloService = helloServiceMap.get("helloServiceImpl");
Assertions.assertNotNull(helloService);
Assertions.assertTrue(
helloService instanceof HelloServiceImpl, "Not expected bean type: " + helloService.getClass());
}
@Order(Integer.MAX_VALUE - 2)
@Configuration
public static class ServiceBeanConfiguration {
@Bean
public HelloService helloServiceImpl() {
return new HelloServiceImpl();
}
}
// make sure that the one using condition runs after.
@Order(Integer.MAX_VALUE - 1)
@Configuration
public static class AnnotationBeanConfiguration {
// TEST Conditional, this bean should be ignored
@Bean
@ConditionalOnMissingBean(HelloService.class)
@DubboReference(group = "${myapp.group}", init = false)
public ReferenceBean<HelloService> helloService() {
return new ReferenceBean();
}
}
}
| 8,654 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.conditional3;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl;
import org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* issue: https://github.com/apache/dubbo-spring-boot-project/issues/779
*/
@SpringBootTest(
properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"},
classes = {JavaConfigRawReferenceBeanConditionalTest.class})
@Configuration
// @ComponentScan
@EnableDubbo
class JavaConfigRawReferenceBeanConditionalTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
void testConsumer() {
Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloService"));
Assertions.assertNull(helloServiceMap.get("myHelloService"));
}
@Order(Integer.MAX_VALUE - 2)
@Configuration
public static class RawReferenceBeanConfiguration {
@Bean
public ReferenceBean<HelloService> helloService() {
return new ReferenceBeanBuilder()
.setGroup("${myapp.group}")
.setInit(false)
.build();
}
}
@Order(Integer.MAX_VALUE - 1)
@Configuration
public static class ConditionalBeanConfiguration {
// TEST Conditional, this bean should be ignored
@Bean
@ConditionalOnMissingBean
public HelloService myHelloService() {
return new HelloServiceImpl();
}
}
}
| 8,655 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.conditional2;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* issue: https://github.com/apache/dubbo-spring-boot-project/issues/779
*/
@SpringBootTest(
properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"},
classes = {JavaConfigAnnotationReferenceBeanConditionalTest.class})
@Configuration
// @ComponentScan
@EnableDubbo
class JavaConfigAnnotationReferenceBeanConditionalTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
void testConsumer() {
Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloService"));
Assertions.assertNull(helloServiceMap.get("myHelloService"));
}
@Order(Integer.MAX_VALUE - 2)
@Configuration
public static class AnnotationBeanConfiguration {
@Bean
@DubboReference(group = "${myapp.group}", init = false)
public ReferenceBean<HelloService> helloService() {
return new ReferenceBean();
}
}
@Order(Integer.MAX_VALUE - 1)
@Configuration
public static class ConditionalBeanConfiguration {
// TEST Conditional, this bean should be ignored
@Bean
@ConditionalOnMissingBean
public HelloService myHelloService() {
return new HelloServiceImpl();
}
}
}
| 8,656 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.importxml2;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.api.HelloService;
@DubboService(group = "${myapp.group:foo2}")
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
| 8,657 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.importxml2;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.apache.dubbo.config.spring.reference.ReferenceBeanManager;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@SpringBootTest(
properties = {
// "dubbo.scan.base-packages=org.apache.dubbo.config.spring.boot.importxml2",
"dubbo.registry.address=N/A",
"myapp.dubbo.port=20881",
"myapp.name=dubbo-provider",
"myapp.group=test"
},
classes = SpringBootImportAndScanTest.class)
@Configuration
@ComponentScan
@DubboComponentScan
@ImportResource("classpath:/org/apache/dubbo/config/spring/boot/importxml2/dubbo-provider.xml")
class SpringBootImportAndScanTest implements ApplicationContextAware {
private ApplicationContext applicationContext;
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@AfterAll
public static void tearDown() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Test
void testProvider() {
String result = helloService.sayHello("dubbo");
Assertions.assertEquals("Hello, dubbo", result);
Map<String, ReferenceBean> referenceBeanMap = applicationContext.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
Assertions.assertNotNull(referenceBeanMap.get("&helloService"));
ReferenceBeanManager referenceBeanManager =
applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class);
Assertions.assertNotNull(referenceBeanManager.getById("helloService"));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Configuration
public static class ConsumerConfiguration {
// Match and reuse 'helloService' reference bean definition in dubbo-provider.xml
@DubboReference(group = "${myapp.group}")
private HelloService helloService;
}
}
| 8,658 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.configprops;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
@SpringBootTest(
properties = {
"dubbo.application.NAME = dubbo-demo-application",
"dubbo.module.name = dubbo-demo-module",
"dubbo.registry.address = zookeeper://192.168.99.100:32770",
"dubbo.protocol.name=dubbo",
"dubbo.protocol.port=20880",
"dubbo.metrics.protocol=prometheus",
"dubbo.metrics.enable-jvm=true",
"dubbo.metrics.prometheus.exporter.enabled=true",
"dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true",
"dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080",
"dubbo.metrics.aggregation.enabled=true",
"dubbo.metrics.aggregation.bucket-num=5",
"dubbo.metrics.aggregation.time-window-seconds=120",
"dubbo.metrics.histogram.enabled=true",
"dubbo.monitor.address=zookeeper://127.0.0.1:32770",
"dubbo.Config-center.address=${zookeeper.connection.address.1}",
"dubbo.config-Center.group=group1",
"dubbo.metadata-report.address=${zookeeper.connection.address.2}",
"dubbo.METADATA-REPORT.username=User",
"dubbo.provider.host=127.0.0.1",
"dubbo.consumer.client=netty"
},
classes = {SpringBootConfigPropsTest.class})
@Configuration
@ComponentScan
@EnableDubbo
class SpringBootConfigPropsTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private ConfigManager configManager;
@Autowired
private ModuleModel moduleModel;
@Test
void testConfigProps() {
ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow();
Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName());
MonitorConfig monitorConfig = configManager.getMonitor().get();
Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress());
MetricsConfig metricsConfig = configManager.getMetrics().get();
Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol());
Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnabled());
Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnableHttpServiceDiscovery());
Assertions.assertEquals(
"localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl());
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
List<ProtocolConfig> defaultProtocols = configManager.getDefaultProtocols();
Assertions.assertEquals(1, defaultProtocols.size());
ProtocolConfig protocolConfig = defaultProtocols.get(0);
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(20880, protocolConfig.getPort());
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
Assertions.assertEquals(1, defaultRegistries.size());
RegistryConfig registryConfig = defaultRegistries.get(0);
Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
ConfigCenterConfig centerConfig = configCenters.iterator().next();
Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress1(), centerConfig.getAddress());
Assertions.assertEquals("group1", centerConfig.getGroup());
Collection<MetadataReportConfig> metadataConfigs = configManager.getMetadataConfigs();
Assertions.assertEquals(1, metadataConfigs.size());
MetadataReportConfig reportConfig = metadataConfigs.iterator().next();
Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress2(), reportConfig.getAddress());
Assertions.assertEquals("User", reportConfig.getUsername());
// module configs
ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager();
ModuleConfig moduleConfig = moduleConfigManager.getModule().get();
Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName());
ProviderConfig providerConfig = moduleConfigManager.getDefaultProvider().get();
Assertions.assertEquals("127.0.0.1", providerConfig.getHost());
ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get();
Assertions.assertEquals("netty", consumerConfig.getClient());
}
}
| 8,659 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.boot.configprops;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
@SpringBootTest(
properties = {
"dubbo.applications.application1.name = dubbo-demo-application",
"dubbo.modules.demo-module.name = dubbo-demo-module",
"dubbo.registries.my-registry.address = zookeeper://192.168.99.100:32770",
"dubbo.protocols.dubbo.port=20880",
"dubbo.metricses.my-metrics.protocol=prometheus",
"dubbo.metricses.my-metrics.prometheus.pushgateway.enabled=true",
"dubbo.metricses.my-metrics.prometheus.pushgateway.base-url=localhost:9091",
"dubbo.metricses.my-metrics.prometheus.pushgateway.username=username",
"dubbo.metricses.my-metrics.prometheus.pushgateway.password=password",
"dubbo.metricses.my-metrics.prometheus.pushgateway.job=job",
"dubbo.metricses.my-metrics.prometheus.pushgateway.push-interval=30",
"dubbo.metricses.my-metrics.aggregation.enabled=true",
"dubbo.metricses.my-metrics.aggregation.bucket-num=5",
"dubbo.metricses.my-metrics.aggregation.time-window-seconds=120",
"dubbo.metricses.my-metrics.histogram.enabled=true",
"dubbo.monitors.my-monitor.address=zookeeper://127.0.0.1:32770",
"dubbo.config-centers.my-configcenter.address=${zookeeper.connection.address.1}",
"dubbo.config-centers.my-configcenter.group=group1",
"dubbo.metadata-reports.my-metadata.address=${zookeeper.connection.address.2}",
"dubbo.metadata-reports.my-metadata.username=User",
"dubbo.providers.my-provider.host=127.0.0.1",
"dubbo.consumers.my-consumer.client=netty"
},
classes = {SpringBootMultipleConfigPropsTest.class})
@Configuration
@ComponentScan
@EnableDubbo
class SpringBootMultipleConfigPropsTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private ConfigManager configManager;
@Autowired
private ModuleModel moduleModel;
@Test
void testConfigProps() {
ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow();
Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName());
MonitorConfig monitorConfig = configManager.getMonitor().get();
Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress());
MetricsConfig metricsConfig = configManager.getMetrics().get();
Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol());
Assertions.assertTrue(metricsConfig.getPrometheus().getPushgateway().getEnabled());
Assertions.assertEquals(
"localhost:9091", metricsConfig.getPrometheus().getPushgateway().getBaseUrl());
Assertions.assertEquals(
"username", metricsConfig.getPrometheus().getPushgateway().getUsername());
Assertions.assertEquals(
"password", metricsConfig.getPrometheus().getPushgateway().getPassword());
Assertions.assertEquals(
"job", metricsConfig.getPrometheus().getPushgateway().getJob());
Assertions.assertEquals(
30, metricsConfig.getPrometheus().getPushgateway().getPushInterval());
Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum());
Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds());
Assertions.assertTrue(metricsConfig.getAggregation().getEnabled());
Assertions.assertTrue(metricsConfig.getHistogram().getEnabled());
List<ProtocolConfig> defaultProtocols = configManager.getDefaultProtocols();
Assertions.assertEquals(1, defaultProtocols.size());
ProtocolConfig protocolConfig = defaultProtocols.get(0);
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(20880, protocolConfig.getPort());
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
Assertions.assertEquals(1, defaultRegistries.size());
RegistryConfig registryConfig = defaultRegistries.get(0);
Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
ConfigCenterConfig centerConfig = configCenters.iterator().next();
Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress1(), centerConfig.getAddress());
Assertions.assertEquals("group1", centerConfig.getGroup());
Collection<MetadataReportConfig> metadataConfigs = configManager.getMetadataConfigs();
Assertions.assertEquals(1, metadataConfigs.size());
MetadataReportConfig reportConfig = metadataConfigs.iterator().next();
Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress2(), reportConfig.getAddress());
Assertions.assertEquals("User", reportConfig.getUsername());
// module configs
ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager();
ModuleConfig moduleConfig = moduleConfigManager.getModule().get();
Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName());
ProviderConfig providerConfig = moduleConfigManager.getDefaultProvider().get();
Assertions.assertEquals("127.0.0.1", providerConfig.getHost());
ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get();
Assertions.assertEquals("netty", consumerConfig.getClient());
}
}
| 8,660 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.propertyconfigurer.consumer2;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.propertyconfigurer.consumer.DemoBeanFactoryPostProcessor;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class PropertySourcesConfigurerTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
void testEarlyInit() {
ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
"org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml");
try {
providerContext.start();
// consumer app
// Resolve placeholder by PropertySourcesPlaceholderConfigurer in dubbo-consumer.xml, without import
// property source.
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
try {
context.start();
HelloService service = (HelloService) context.getBean("demoService");
String result = service.sayHello("world");
System.out.println("result: " + result);
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0),
result);
} finally {
context.close();
}
} finally {
providerContext.close();
}
}
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.propertyconfigurer.consumer2")
@ComponentScan(value = {"org.apache.dubbo.config.spring.propertyconfigurer.consumer2"})
@ImportResource("classpath:/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/dubbo-consumer.xml")
static class ConsumerConfiguration {
@Bean
public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService service) {
return new DemoBeanFactoryPostProcessor(service);
}
}
}
| 8,661 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.propertyconfigurer.consumer3;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.propertyconfigurer.consumer.DemoBeanFactoryPostProcessor;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
class PropertySourcesInJavaConfigTest {
private static final String SCAN_PACKAGE_NAME =
"org.apache.dubbo.config.spring.propertyconfigurer.consumer3.notexist";
private static final String PACKAGE_PATH = "/org/apache/dubbo/config/spring/propertyconfigurer/consumer3";
private static final String PROVIDER_CONFIG_PATH =
"org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml";
@BeforeEach
public void setUp() throws Exception {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
}
@BeforeEach
public void beforeTest() {
DubboBootstrap.reset();
}
@Test
void testImportPropertySource() {
ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(PROVIDER_CONFIG_PATH);
try {
providerContext.start();
// Resolve placeholder by import property sources
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
ConsumerConfiguration.class, ImportPropertyConfiguration.class);
try {
// expect auto create PropertySourcesPlaceholderConfigurer bean
String[] beanNames = context.getBeanNamesForType(PropertySourcesPlaceholderConfigurer.class);
Assertions.assertEquals(1, beanNames.length);
Assertions.assertEquals(PropertySourcesPlaceholderConfigurer.class.getName(), beanNames[0]);
HelloService service = (HelloService) context.getBean("demoService");
String result = service.sayHello("world");
System.out.println("result: " + result);
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0),
result);
} finally {
context.close();
}
} finally {
providerContext.close();
}
}
@Test
void testCustomPropertySourceBean() {
ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(PROVIDER_CONFIG_PATH);
try {
providerContext.start();
// Resolve placeholder by custom PropertySourcesPlaceholderConfigurer bean
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
ConsumerConfiguration.class, PropertyBeanConfiguration.class);
try {
// expect using custom PropertySourcesPlaceholderConfigurer bean
String[] beanNames = context.getBeanNamesForType(PropertySourcesPlaceholderConfigurer.class);
Assertions.assertEquals(1, beanNames.length);
Assertions.assertEquals("myPropertySourcesPlaceholderConfigurer", beanNames[0]);
HelloService service = (HelloService) context.getBean("demoService");
String result = service.sayHello("world");
System.out.println("result: " + result);
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0),
result);
} finally {
context.close();
}
} finally {
providerContext.close();
}
}
@Configuration
@EnableDubbo(scanBasePackages = SCAN_PACKAGE_NAME)
@ComponentScan(value = {SCAN_PACKAGE_NAME})
@ImportResource("classpath:" + PACKAGE_PATH + "/dubbo-consumer.xml")
static class ConsumerConfiguration {
@Bean
public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService service) {
return new DemoBeanFactoryPostProcessor(service);
}
}
@Configuration
@PropertySource("classpath:" + PACKAGE_PATH + "/app.properties")
static class ImportPropertyConfiguration {}
@Configuration
static class PropertyBeanConfiguration {
@Bean
public MyPropertySourcesPlaceholderConfigurer myPropertySourcesPlaceholderConfigurer() {
MyPropertySourcesPlaceholderConfigurer placeholderConfigurer = new MyPropertySourcesPlaceholderConfigurer();
placeholderConfigurer.setLocation(new ClassPathResource(PACKAGE_PATH + "/app.properties"));
return placeholderConfigurer;
}
}
static class MyPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
@Override
protected String convertProperty(String propertyName, String propertyValue) {
// .. do something ..
return propertyValue;
}
}
}
| 8,662 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.propertyconfigurer.provider;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloServiceImpl implements HelloService {
private static final Logger logger = LoggerFactory.getLogger(HelloServiceImpl.class);
@Override
public String sayHello(String name) {
logger.info("Hello " + name + ", request from consumer: "
+ RpcContext.getContext().getRemoteAddress());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello " + name + ", response from provider: "
+ RpcContext.getContext().getLocalAddress();
}
}
| 8,663 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.propertyconfigurer.consumer;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class PropertyConfigurerTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
void testEarlyInit() {
ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
"org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml");
try {
providerContext.start();
// Resolve placeholder by PropertyPlaceholderConfigurer in dubbo-consumer.xml, without import property
// source.
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
context.start();
HelloService service = (HelloService) context.getBean("demoService");
String result = service.sayHello("world");
System.out.println("result: " + result);
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0),
result);
context.close();
} finally {
providerContext.close();
}
}
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.propertyconfigurer.consumer")
@ComponentScan(value = {"org.apache.dubbo.config.spring.propertyconfigurer.consumer"})
@ImportResource("classpath:/org/apache/dubbo/config/spring/propertyconfigurer/consumer/dubbo-consumer.xml")
static class ConsumerConfiguration {
@Bean
public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService service) {
return new DemoBeanFactoryPostProcessor(service);
}
}
}
| 8,664 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/DemoBeanFactoryPostProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.propertyconfigurer.consumer;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.PriorityOrdered;
public class DemoBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {
private HelloService demoService;
public DemoBeanFactoryPostProcessor(HelloService demoService) {
this.demoService = demoService;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (demoService == null) {
throw new IllegalStateException("demoService is not injected");
}
System.out.println("DemoBeanFactoryPostProcessor");
}
/**
* call before PropertyPlaceholderConfigurer
*/
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
| 8,665 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/util/EnvironmentUtilsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.util;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.mock.env.MockEnvironment;
import static org.apache.dubbo.config.spring.util.EnvironmentUtils.filterDubboProperties;
/**
* {@link EnvironmentUtils} Test
*
* @see EnvironmentUtils
* @since 2.7.0
*/
class EnvironmentUtilsTest {
@Test
void testExtraProperties() {
String key = "test.name";
System.setProperty(key, "Tom");
try {
StandardEnvironment environment = new StandardEnvironment();
Map<String, Object> map = new HashMap<>();
map.put(key, "Mercy");
MapPropertySource propertySource = new MapPropertySource("first", map);
CompositePropertySource compositePropertySource = new CompositePropertySource("comp");
compositePropertySource.addFirstPropertySource(propertySource);
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addFirst(compositePropertySource);
Map<String, Object> properties = EnvironmentUtils.extractProperties(environment);
Assertions.assertEquals("Mercy", properties.get(key));
} finally {
System.clearProperty(key);
}
}
@Test
void testFilterDubboProperties() {
MockEnvironment environment = new MockEnvironment();
environment.setProperty("message", "Hello,World");
environment.setProperty("dubbo.registry.address", "zookeeper://10.10.10.1:2181");
environment.setProperty("dubbo.consumer.check", "false");
SortedMap<String, String> dubboProperties = filterDubboProperties(environment);
Assertions.assertEquals(2, dubboProperties.size());
Assertions.assertEquals("zookeeper://10.10.10.1:2181", dubboProperties.get("dubbo.registry.address"));
Assertions.assertEquals("false", dubboProperties.get("dubbo.consumer.check"));
}
}
| 8,666 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.annotation.provider;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
/**
* DemoServiceImpl
*/
@Service(version = "${provider.version}")
public class AnnotationServiceImpl implements DemoService {
public String sayName(String name) {
return "annotation:" + name;
}
public Box getBox() {
return null;
}
}
| 8,667 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.annotation.consumer;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.spring.api.DemoService;
import org.springframework.stereotype.Controller;
/**
* AnnotationAction
*/
@Controller("annotationAction")
public class AnnotationAction {
@Reference(
version = "1.2",
methods = {@Method(name = "sayName", timeout = 5000)})
private DemoService demoService;
public String doSayName(String name) {
return demoService.sayName(name);
}
}
| 8,668 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.annotation.merged;
import org.apache.dubbo.config.annotation.Service;
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;
import org.springframework.core.annotation.AliasFor;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Service
public @interface MergedService {
@AliasFor(annotation = Service.class, attribute = "group")
String group() default "dubbo";
@AliasFor(annotation = Service.class, attribute = "version")
String version() default "1.0.0";
}
| 8,669 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.annotation.merged;
import org.apache.dubbo.config.annotation.Reference;
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;
import org.springframework.core.annotation.AliasFor;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Reference
public @interface MergedReference {
@AliasFor(annotation = Reference.class, attribute = "group")
String group() default "dubbo";
@AliasFor(annotation = Reference.class, attribute = "version")
String version() default "1.0.0";
}
| 8,670 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.status;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.config.spring.ServiceBean;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.MockitoAnnotations.initMocks;
class DataSourceStatusCheckerTest {
private DataSourceStatusChecker dataSourceStatusChecker;
@Mock
private ApplicationContext applicationContext;
@BeforeEach
public void setUp() throws Exception {
initMocks(this);
this.dataSourceStatusChecker = new DataSourceStatusChecker(applicationContext);
new ServiceBean<Object>(applicationContext).setApplicationContext(applicationContext);
}
@AfterEach
public void tearDown() throws Exception {
Mockito.reset(applicationContext);
}
@Test
void testWithoutApplicationContext() {
Status status = dataSourceStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.UNKNOWN));
}
@Test
void testWithoutDatasource() {
Map<String, DataSource> map = new HashMap<String, DataSource>();
given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean()))
.willReturn(map);
Status status = dataSourceStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.UNKNOWN));
}
@Test
void testWithDatasourceHasNextResult() throws SQLException {
Map<String, DataSource> map = new HashMap<String, DataSource>();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS);
given(dataSource.getConnection()).willReturn(connection);
given(connection.getMetaData().getTypeInfo().next()).willReturn(true);
map.put("mockDatabase", dataSource);
given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean()))
.willReturn(map);
Status status = dataSourceStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.OK));
}
@Test
void testWithDatasourceNotHasNextResult() throws SQLException {
Map<String, DataSource> map = new HashMap<String, DataSource>();
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS);
given(dataSource.getConnection()).willReturn(connection);
given(connection.getMetaData().getTypeInfo().next()).willReturn(false);
map.put("mockDatabase", dataSource);
given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean()))
.willReturn(map);
Status status = dataSourceStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.ERROR));
}
}
| 8,671 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.status;
import org.apache.dubbo.common.status.Status;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.Lifecycle;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class SpringStatusCheckerTest {
// @Mock
// private ApplicationLifeCycle applicationContext;
@BeforeEach
public void setUp() throws Exception {
// initMocks(this);
}
@AfterEach
public void tearDown() throws Exception {
// Mockito.reset(applicationContext);
}
@Test
void testWithoutApplicationContext() {
SpringStatusChecker springStatusChecker = new SpringStatusChecker((ApplicationContext) null);
Status status = springStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.UNKNOWN));
}
@Test
void testWithLifeCycleRunning() {
ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class);
given(applicationLifeCycle.getConfigLocations()).willReturn(new String[] {"test1", "test2"});
given(applicationLifeCycle.isRunning()).willReturn(true);
SpringStatusChecker springStatusChecker = new SpringStatusChecker(applicationLifeCycle);
Status status = springStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.OK));
assertThat(status.getMessage(), is("test1,test2"));
}
@Test
void testWithoutLifeCycleRunning() {
ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class);
given(applicationLifeCycle.isRunning()).willReturn(false);
SpringStatusChecker springStatusChecker = new SpringStatusChecker(applicationLifeCycle);
Status status = springStatusChecker.check();
assertThat(status.getLevel(), is(Status.Level.ERROR));
}
interface ApplicationLifeCycle extends Lifecycle, ApplicationContext {
String[] getConfigLocations();
}
// TODO improve GenericWebApplicationContext test scenario
@Test
void testGenericWebApplicationContext() {
GenericWebApplicationContext context = mock(GenericWebApplicationContext.class);
given(context.isRunning()).willReturn(true);
SpringStatusChecker checker = new SpringStatusChecker(context);
Status status = checker.check();
Assertions.assertEquals(Status.Level.OK, status.getLevel());
}
}
| 8,672 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/samples/ZookeeperDubboSpringConsumerBootstrap.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.samples;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.PropertySource;
/**
* Zookeeper Dubbo Spring Provider Bootstrap
*
* @since 2.7.8
*/
@EnableDubboConfig
@PropertySource("classpath:/META-INF/service-introspection/zookeeper-dubbb-consumer.properties")
public class ZookeeperDubboSpringConsumerBootstrap {
@DubboReference(services = "${dubbo.provider.name},${dubbo.provider.name1},${dubbo.provider.name2}")
private DemoService demoService;
public static void main(String[] args) throws Exception {
Class<?> beanType = ZookeeperDubboSpringConsumerBootstrap.class;
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(beanType);
ZookeeperDubboSpringConsumerBootstrap bootstrap = context.getBean(ZookeeperDubboSpringConsumerBootstrap.class);
for (int i = 0; i < 100; i++) {
System.out.println(bootstrap.demoService.sayName("Hello"));
Thread.sleep(1000L);
}
System.in.read();
context.close();
}
}
| 8,673 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/samples/ZookeeperDubboSpringConsumerXmlBootstrap.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.samples;
import org.apache.dubbo.config.spring.api.DemoService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Zookeeper Dubbo Spring Provider XML Bootstrap
*
* @since 2.7.8
*/
public class ZookeeperDubboSpringConsumerXmlBootstrap {
public static void main(String[] args) throws Exception {
String location = "classpath:/META-INF/service-introspection/zookeeper-dubbo-consumer.xml";
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(location);
DemoService demoService = context.getBean("demoService", DemoService.class);
for (int i = 0; i < 100; i++) {
System.out.println(demoService.sayName("Hello"));
}
context.close();
}
}
| 8,674 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/samples/ZookeeperDubboSpringProviderBootstrap.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.samples;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.PropertySource;
import static java.lang.String.format;
/**
* Zookeeper Dubbo Spring Provider Bootstrap
*
* @since 2.7.8
*/
@EnableDubbo
@PropertySource("classpath:/META-INF/service-introspection/zookeeper-dubbb-provider.properties")
public class ZookeeperDubboSpringProviderBootstrap {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ZookeeperDubboSpringProviderBootstrap.class);
System.in.read();
context.close();
}
}
@DubboService
class DefaultDemoService implements DemoService {
@Override
public String sayName(String name) {
RpcContext rpcContext = RpcContext.getServiceContext();
return format("[%s:%s] Say - %s", rpcContext.getLocalHost(), rpcContext.getLocalPort(), name);
}
@Override
public Box getBox() {
return null;
}
}
| 8,675 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DubboNamespaceHandlerTest {
private static String resourcePath = "org.apache.dubbo.config.spring".replace('.', '/');
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
DubboBootstrap.reset();
}
@Configuration
@PropertySource("classpath:/META-INF/demo-provider.properties")
@ImportResource(locations = "classpath:/org/apache/dubbo/config/spring/demo-provider.xml")
static class XmlConfiguration {}
@Test
void testProviderXmlOnConfigurationClass() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(XmlConfiguration.class);
applicationContext.refresh();
testProviderXml(applicationContext);
}
@Test
void testProviderXml() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml");
ctx.start();
testProviderXml(ctx);
}
private void testProviderXml(ApplicationContext context) {
String appName = "demo-provider";
String configId = ApplicationConfig.class.getName() + "#" + appName + "#0";
Map<String, ApplicationConfig> applicationConfigMap = context.getBeansOfType(ApplicationConfig.class);
ApplicationConfig providerAppConfig = context.getBean(configId, ApplicationConfig.class);
assertNotNull(providerAppConfig);
assertEquals(appName, providerAppConfig.getName());
// assertEquals(configId, providerAppConfig.getId());
ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class);
assertThat(protocolConfig, not(nullValue()));
assertThat(protocolConfig.getName(), is("dubbo"));
assertThat(protocolConfig.getPort(), is(20813));
ApplicationConfig applicationConfig = context.getBean(ApplicationConfig.class);
assertThat(applicationConfig, not(nullValue()));
assertThat(applicationConfig.getName(), is("demo-provider"));
RegistryConfig registryConfig = context.getBean(RegistryConfig.class);
assertThat(registryConfig, not(nullValue()));
assertThat(registryConfig.getAddress(), is("N/A"));
DemoService service = context.getBean(DemoService.class);
assertThat(service, not(nullValue()));
}
@Test
void testMultiProtocol() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol.xml");
ctx.start();
Map<String, ProtocolConfig> protocolConfigMap = ctx.getBeansOfType(ProtocolConfig.class);
assertThat(protocolConfigMap.size(), is(2));
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
Collection<ProtocolConfig> protocolConfigs = configManager.getProtocols();
assertThat(protocolConfigs.size(), is(2));
ProtocolConfig rmiProtocolConfig = configManager.getProtocol("rmi").get();
assertThat(rmiProtocolConfig.getPort(), is(10991));
ProtocolConfig dubboProtocolConfig = configManager.getProtocol("dubbo").get();
assertThat(dubboProtocolConfig.getPort(), is(20881));
}
@Test
void testDefaultProtocol() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml");
ctx.start();
ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class);
protocolConfig.refresh();
assertThat(protocolConfig.getName(), is("dubbo"));
}
@Test
void testCustomParameter() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/customize-parameter.xml");
ctx.start();
ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class);
assertThat(protocolConfig.getParameters().size(), is(1));
assertThat(protocolConfig.getParameters().get("protocol-paramA"), is("protocol-paramA"));
ServiceBean serviceBean = ctx.getBean(ServiceBean.class);
assertThat(serviceBean.getParameters().size(), is(1));
assertThat(serviceBean.getParameters().get("service-paramA"), is("service-paramA"));
}
@Test
void testDelayFixedTime() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("classpath:/" + resourcePath + "/delay-fixed-time.xml");
ctx.start();
assertThat(ctx.getBean(ServiceBean.class).getDelay(), is(300));
}
@Test
void testTimeoutConfig() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml");
ctx.start();
ModuleConfigManager configManager =
ApplicationModel.defaultModel().getDefaultModule().getConfigManager();
Collection<ProviderConfig> providerConfigs = configManager.getProviders();
Assertions.assertEquals(2, providerConfigs.size());
ProviderConfig defaultProvider = configManager.getDefaultProvider().get();
assertThat(defaultProvider.getTimeout(), is(2000));
ProviderConfig provider2 = configManager.getProvider("provider2").get();
ServiceConfigBase<Object> serviceConfig2 = configManager.getService("serviceConfig2");
Assertions.assertEquals(1000, provider2.getTimeout());
Assertions.assertEquals(provider2.getTimeout(), serviceConfig2.getTimeout());
}
@Test
void testMonitor() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/provider-with-monitor.xml");
ctx.start();
assertThat(ctx.getBean(MonitorConfig.class), not(nullValue()));
}
// @Test
// public void testMultiMonitor() {
// Assertions.assertThrows(BeanCreationException.class, () -> {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath +
// "/multi-monitor.xml");
// ctx.start();
// });
// }
//
// @Test
// public void testMultiProviderConfig() {
// Assertions.assertThrows(BeanCreationException.class, () -> {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath +
// "/provider-multi.xml");
// ctx.start();
// });
// }
@Test
void testModuleInfo() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/provider-with-module.xml");
ctx.start();
ModuleConfig moduleConfig = ctx.getBean(ModuleConfig.class);
assertThat(moduleConfig.getName(), is("test-module"));
}
@Test
void testNotificationWithWrongBean() {
Assertions.assertThrows(BeanCreationException.class, () -> {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/consumer-notification.xml");
ctx.start();
});
}
@Test
void testProperty() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/service-class.xml");
ctx.start();
ServiceBean serviceBean = ctx.getBean(ServiceBean.class);
String prefix = ((DemoServiceImpl) serviceBean.getRef()).getPrefix();
assertThat(prefix, is("welcome:"));
}
@Test
void testMetricsAggregation() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/metrics-aggregation.xml");
ctx.start();
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
MetricsConfig metricsBean = ctx.getBean(MetricsConfig.class);
MetricsConfig metrics = configManager.getMetrics().get();
assertTrue(metrics.getEnableJvm());
assertEquals(metrics.getAggregation().getEnabled(), true);
assertEquals(metrics.getAggregation().getBucketNum(), 5);
assertEquals(metrics.getAggregation().getTimeWindowSeconds(), 120);
assertEquals(
metrics.getAggregation().getEnabled(),
metricsBean.getAggregation().getEnabled());
assertEquals(
metrics.getAggregation().getBucketNum(),
metricsBean.getAggregation().getBucketNum());
assertEquals(
metrics.getAggregation().getTimeWindowSeconds(),
metricsBean.getAggregation().getTimeWindowSeconds());
}
@Test
void testMetricsPrometheus() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(resourcePath + "/metrics-prometheus.xml");
ctx.start();
ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager();
MetricsConfig metricsBean = ctx.getBean(MetricsConfig.class);
MetricsConfig metrics = configManager.getMetrics().get();
assertEquals(metrics.getProtocol(), PROTOCOL_PROMETHEUS);
assertEquals(metrics.getPrometheus().getExporter().getEnabled(), true);
assertEquals(metrics.getPrometheus().getExporter().getEnableHttpServiceDiscovery(), true);
assertEquals(metrics.getPrometheus().getExporter().getHttpServiceDiscoveryUrl(), "localhost:8080");
assertEquals(metrics.getPrometheus().getPushgateway().getEnabled(), true);
assertEquals(metrics.getPrometheus().getPushgateway().getBaseUrl(), "localhost:9091");
assertEquals(metrics.getPrometheus().getPushgateway().getPushInterval(), 30);
assertEquals(metrics.getPrometheus().getPushgateway().getUsername(), "username");
assertEquals(metrics.getPrometheus().getPushgateway().getPassword(), "password");
assertEquals(metrics.getPrometheus().getPushgateway().getJob(), "job");
assertEquals(metricsBean.getProtocol(), PROTOCOL_PROMETHEUS);
assertEquals(metricsBean.getPrometheus().getExporter().getEnabled(), true);
assertEquals(metricsBean.getPrometheus().getExporter().getEnableHttpServiceDiscovery(), true);
assertEquals(metricsBean.getPrometheus().getExporter().getHttpServiceDiscoveryUrl(), "localhost:8080");
assertEquals(metricsBean.getPrometheus().getPushgateway().getEnabled(), true);
assertEquals(metricsBean.getPrometheus().getPushgateway().getBaseUrl(), "localhost:9091");
assertEquals(metricsBean.getPrometheus().getPushgateway().getPushInterval(), 30);
assertEquals(metricsBean.getPrometheus().getPushgateway().getUsername(), "username");
assertEquals(metricsBean.getPrometheus().getPushgateway().getPassword(), "password");
assertEquals(metricsBean.getPrometheus().getPushgateway().getJob(), "job");
}
}
| 8,676 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.config.ServiceConfigBase;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.rpc.service.GenericService;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = GenericServiceTest.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@ImportResource(locations = "classpath:/META-INF/spring/dubbo-generic-consumer.xml")
class GenericServiceTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
@Qualifier("demoServiceRef")
private GenericService demoServiceRef;
@Autowired
@Qualifier("demoService")
private ServiceBean serviceBean;
@Test
void testGeneric() {
assertNotNull(demoServiceRef);
assertNotNull(serviceBean);
ModuleConfigManager configManager = DubboBootstrap.getInstance()
.getApplicationModel()
.getDefaultModule()
.getConfigManager();
ServiceConfigBase<Object> serviceConfig = configManager.getService("demoService");
Assertions.assertEquals(DemoService.class.getName(), serviceConfig.getInterface());
Assertions.assertEquals(true, serviceConfig.isExported());
Object result = demoServiceRef.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"dubbo"});
Assertions.assertEquals("Welcome dubbo", result);
}
}
| 8,677 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.service.GenericService;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = GenericServiceWithoutInterfaceTest.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@ImportResource(locations = "classpath:/META-INF/spring/dubbo-generic-consumer-without-interface.xml")
class GenericServiceWithoutInterfaceTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
@Qualifier("genericServiceWithoutInterfaceRef")
private GenericService genericServiceWithoutInterfaceRef;
@Test
void testGenericWithoutInterface() {
// Test generic service without interface class locally
Object result = genericServiceWithoutInterfaceRef.$invoke(
"sayHello", new String[] {"java.lang.String"}, new Object[] {"generic"});
Assertions.assertEquals("Welcome generic", result);
ReferenceConfigBase<Object> reference = DubboBootstrap.getInstance()
.getApplicationModel()
.getDefaultModule()
.getConfigManager()
.getReference("genericServiceWithoutInterfaceRef");
Assertions.assertNull(reference.getServiceInterfaceClass());
Assertions.assertEquals("org.apache.dubbo.config.spring.api.LocalMissClass", reference.getInterface());
Assertions.assertThrows(ClassNotFoundException.class, () -> ClassUtils.forName(reference.getInterface()));
}
}
| 8,678 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/MyGenericService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
public class MyGenericService implements GenericService {
public Object $invoke(String methodName, String[] parameterTypes, Object[] args) throws GenericException {
if ("sayHello".equals(methodName)) {
return "Welcome " + args[0];
}
return null;
}
}
| 8,679 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionBySetter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.action;
import org.apache.dubbo.config.spring.api.DemoService;
/**
* DemoAction
*/
public class DemoActionBySetter {
private DemoService demoService;
public DemoService getDemoService() {
return demoService;
}
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
}
| 8,680 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoInterceptor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.action;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* DemoInterceptor
*/
public class DemoInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
return "aop:" + invocation.proceed();
}
}
| 8,681 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/action/DemoActionByAnnotation.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.action;
import org.apache.dubbo.config.spring.api.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* DemoAction
*/
public class DemoActionByAnnotation {
@Autowired
private DemoService demoService;
public DemoService getDemoService() {
return demoService;
}
}
| 8,682 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/api/ApiIsolationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.api;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.IsolationExecutorRepository;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.config.spring.impl.HelloServiceImpl;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
public class ApiIsolationTest {
private static RegistryConfig registryConfig;
@BeforeAll
public static void beforeAll() {
FrameworkModel.destroyAll();
registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1());
}
@AfterAll
public static void afterAll() throws Exception {
FrameworkModel.destroyAll();
}
private String version1 = "1.0";
private String version2 = "2.0";
private String version3 = "3.0";
@Test
@Disabled
public void test() throws Exception {
DubboBootstrap providerBootstrap = null;
DubboBootstrap consumerBootstrap1 = null;
DubboBootstrap consumerBootstrap2 = null;
try {
// provider app
providerBootstrap = DubboBootstrap.newInstance();
ServiceConfig serviceConfig1 = new ServiceConfig();
serviceConfig1.setInterface(DemoService.class);
serviceConfig1.setRef(new DemoServiceImpl());
serviceConfig1.setVersion(version1);
// set executor1 for serviceConfig1, max threads is 10
NamedThreadFactory threadFactory1 = new NamedThreadFactory("DemoService-executor");
ExecutorService executor1 = Executors.newFixedThreadPool(10, threadFactory1);
serviceConfig1.setExecutor(executor1);
ServiceConfig serviceConfig2 = new ServiceConfig();
serviceConfig2.setInterface(HelloService.class);
serviceConfig2.setRef(new HelloServiceImpl());
serviceConfig2.setVersion(version2);
// set executor2 for serviceConfig2, max threads is 100
NamedThreadFactory threadFactory2 = new NamedThreadFactory("HelloService-executor");
ExecutorService executor2 = Executors.newFixedThreadPool(100, threadFactory2);
serviceConfig2.setExecutor(executor2);
ServiceConfig serviceConfig3 = new ServiceConfig();
serviceConfig3.setInterface(HelloService.class);
serviceConfig3.setRef(new HelloServiceImpl());
serviceConfig3.setVersion(version3);
// Because executor is not set for serviceConfig3, the default executor of serviceConfig3 is built using
// the threadpool parameter of the protocolConfig ( FixedThreadpool , max threads is 200)
serviceConfig3.setExecutor(null);
// It takes effect only if [executor-management-mode=isolation] is configured
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_ISOLATION);
providerBootstrap
.application(applicationConfig)
.registry(registryConfig)
// export with tri and dubbo protocol
.protocol(new ProtocolConfig("tri", 20001))
.protocol(new ProtocolConfig("dubbo", 20002))
.service(serviceConfig1)
.service(serviceConfig2)
.service(serviceConfig3);
providerBootstrap.start();
// Verify that the executor is the previously configured
ApplicationModel applicationModel = providerBootstrap.getApplicationModel();
ExecutorRepository repository = ExecutorRepository.getInstance(applicationModel);
Assertions.assertTrue(repository instanceof IsolationExecutorRepository);
Assertions.assertEquals(executor1, repository.getExecutor(serviceConfig1.toUrl()));
Assertions.assertEquals(executor2, repository.getExecutor(serviceConfig2.toUrl()));
// the default executor of serviceConfig3 is built using the threadpool parameter of the protocol
ThreadPoolExecutor executor3 = (ThreadPoolExecutor) repository.getExecutor(serviceConfig3.toUrl());
Assertions.assertTrue(executor3.getThreadFactory() instanceof NamedInternalThreadFactory);
NamedInternalThreadFactory threadFactory3 = (NamedInternalThreadFactory) executor3.getThreadFactory();
// consumer app start with dubbo protocol and rpc call
consumerBootstrap1 = configConsumerBootstrapWithProtocol("dubbo");
rpcInvoke(consumerBootstrap1);
// consumer app start with tri protocol and rpc call
consumerBootstrap2 = configConsumerBootstrapWithProtocol("tri");
rpcInvoke(consumerBootstrap2);
// Verify that when the provider accepts different service requests,
// whether to use the respective executor(threadFactory) of different services to create threads
AtomicInteger threadNum1 = threadFactory1.getThreadNum();
AtomicInteger threadNum2 = threadFactory2.getThreadNum();
AtomicInteger threadNum3 = threadFactory3.getThreadNum();
Assertions.assertEquals(threadNum1.get(), 11);
Assertions.assertEquals(threadNum2.get(), 101);
Assertions.assertEquals(threadNum3.get(), 201);
} finally {
if (providerBootstrap != null) {
providerBootstrap.destroy();
}
if (consumerBootstrap1 != null) {
consumerBootstrap1.destroy();
}
if (consumerBootstrap2 != null) {
consumerBootstrap2.destroy();
}
}
}
private void rpcInvoke(DubboBootstrap consumerBootstrap) {
DemoService demoServiceV1 = consumerBootstrap.getCache().get(DemoService.class.getName() + ":" + version1);
HelloService helloServiceV2 = consumerBootstrap.getCache().get(HelloService.class.getName() + ":" + version2);
HelloService helloServiceV3 = consumerBootstrap.getCache().get(HelloService.class.getName() + ":" + version3);
for (int i = 0; i < 250; i++) {
demoServiceV1.sayName("name, version = " + version1);
}
for (int i = 0; i < 250; i++) {
helloServiceV2.sayHello("hello, version = " + version2);
}
for (int i = 0; i < 250; i++) {
helloServiceV3.sayHello("hello, version = " + version3);
}
}
private DubboBootstrap configConsumerBootstrapWithProtocol(String protocol) {
DubboBootstrap consumerBootstrap;
consumerBootstrap = DubboBootstrap.newInstance();
consumerBootstrap
.application("consumer-app")
.registry(registryConfig)
.reference(builder -> builder.interfaceClass(DemoService.class)
.version(version1)
.protocol(protocol)
.injvm(false))
.reference(builder -> builder.interfaceClass(HelloService.class)
.version(version2)
.protocol(protocol)
.injvm(false))
.reference(builder -> builder.interfaceClass(HelloService.class)
.version(version3)
.protocol(protocol)
.injvm(false));
consumerBootstrap.start();
return consumerBootstrap;
}
}
| 8,683 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/BaseTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.IsolationExecutorRepository;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.isolation.spring.support.DemoServiceExecutor;
import org.apache.dubbo.config.spring.isolation.spring.support.HelloServiceExecutor;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
public abstract class BaseTest {
protected ServiceConfig serviceConfig1;
protected ServiceConfig serviceConfig2;
protected ServiceConfig serviceConfig3;
@Test
public void test() throws Exception {
test();
}
protected void assertExecutor(ApplicationContext providerContext, ApplicationContext consumerContext) {
// find configured "executor-demo-service" executor
Map<String, DemoServiceExecutor> beansOfType1 = providerContext.getBeansOfType(DemoServiceExecutor.class);
ThreadPoolExecutor executor1 = beansOfType1.get("executor-demo-service");
NamedThreadFactory threadFactory1 = (NamedThreadFactory) executor1.getThreadFactory();
// find configured "executor-hello-service" executor
Map<String, HelloServiceExecutor> beansOfType2 = providerContext.getBeansOfType(HelloServiceExecutor.class);
ThreadPoolExecutor executor2 = beansOfType2.get("executor-hello-service");
NamedThreadFactory threadFactory2 = (NamedThreadFactory) executor2.getThreadFactory();
// Verify that the executor is the previously configured
Map<String, ApplicationModel> applicationModelMap = providerContext.getBeansOfType(ApplicationModel.class);
ApplicationModel applicationModel = applicationModelMap.get(ApplicationModel.class.getName());
ExecutorRepository repository = ExecutorRepository.getInstance(applicationModel);
Assertions.assertTrue(repository instanceof IsolationExecutorRepository);
Assertions.assertEquals(executor1, repository.getExecutor(serviceConfig1.toUrl()));
Assertions.assertEquals(executor2, repository.getExecutor(serviceConfig2.toUrl()));
// the default executor of serviceConfig3 is built using the threadpool parameter of the protocol
ThreadPoolExecutor executor3 = (ThreadPoolExecutor) repository.getExecutor(serviceConfig3.toUrl());
Assertions.assertTrue(executor3.getThreadFactory() instanceof NamedInternalThreadFactory);
NamedInternalThreadFactory threadFactory3 = (NamedInternalThreadFactory) executor3.getThreadFactory();
// rpc invoke with dubbo protocol
DemoService demoServiceV1 = consumerContext.getBean("dubbo-demoServiceV1", DemoService.class);
HelloService helloServiceV2 = consumerContext.getBean("dubbo-helloServiceV2", HelloService.class);
HelloService helloServiceV3 = consumerContext.getBean("dubbo-helloServiceV3", HelloService.class);
rpcInvoke(demoServiceV1, helloServiceV2, helloServiceV3);
// rpc invoke with tri protocol
demoServiceV1 = consumerContext.getBean("tri-demoServiceV1", DemoService.class);
helloServiceV2 = consumerContext.getBean("tri-helloServiceV2", HelloService.class);
helloServiceV3 = consumerContext.getBean("tri-helloServiceV3", HelloService.class);
rpcInvoke(demoServiceV1, helloServiceV2, helloServiceV3);
// Verify that when the provider accepts different service requests,
// whether to use the respective executor(threadFactory) of different services to create threads
AtomicInteger threadNum1 = threadFactory1.getThreadNum();
AtomicInteger threadNum2 = threadFactory2.getThreadNum();
AtomicInteger threadNum3 = threadFactory3.getThreadNum();
Assertions.assertEquals(threadNum1.get(), 11);
Assertions.assertEquals(threadNum2.get(), 101);
Assertions.assertEquals(threadNum3.get(), 201);
}
private void rpcInvoke(DemoService demoServiceV1, HelloService helloServiceV2, HelloService helloServiceV3) {
for (int i = 0; i < 250; i++) {
demoServiceV1.sayName("name");
}
for (int i = 0; i < 250; i++) {
helloServiceV2.sayHello("hello");
}
for (int i = 0; i < 250; i++) {
helloServiceV3.sayHello("hello");
}
}
}
| 8,684 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/AnnotationIsolationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.isolation.spring.BaseTest;
import org.apache.dubbo.config.spring.isolation.spring.support.DemoServiceExecutor;
import org.apache.dubbo.config.spring.isolation.spring.support.HelloServiceExecutor;
import java.util.Map;
import java.util.concurrent.Executor;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
public class AnnotationIsolationTest extends BaseTest {
@Test
public void test() throws Exception {
// start provider app
AnnotationConfigApplicationContext providerContext =
new AnnotationConfigApplicationContext(ProviderConfiguration.class);
providerContext.start();
// start consumer app
AnnotationConfigApplicationContext consumerContext =
new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
consumerContext.start();
// getAndSet serviceConfig
setServiceConfig(providerContext);
// assert isolation of executor
assertExecutor(providerContext, consumerContext);
// close context
providerContext.close();
consumerContext.close();
}
private void setServiceConfig(AnnotationConfigApplicationContext providerContext) {
Map<String, ServiceConfig> serviceConfigMap = providerContext.getBeansOfType(ServiceConfig.class);
serviceConfig1 =
serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:Group1");
serviceConfig2 =
serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.HelloService:2.0.0:Group2");
serviceConfig3 =
serviceConfigMap.get("ServiceBean:org.apache.dubbo.config.spring.api.HelloService:3.0.0:Group3");
}
// note scanBasePackages, refer three service with dubbo and tri protocol
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.demo.consumer.comp")
@ComponentScan(value = {"org.apache.dubbo.config.spring.isolation.spring.annotation.consumer"})
static class ConsumerConfiguration {
@Bean
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("zookeeper://127.0.0.1:2181");
return registryConfig;
}
@Bean
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig("consumer-app");
return applicationConfig;
}
}
// note scanBasePackages, expose three service with dubbo and tri protocol
@Configuration
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.isolation.spring.annotation.provider")
static class ProviderConfiguration {
@Bean
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("zookeeper://127.0.0.1:2181");
return registryConfig;
}
// NOTE: we need config executor-management-mode="isolation"
@Bean
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_ISOLATION);
return applicationConfig;
}
// expose services with dubbo protocol
@Bean
public ProtocolConfig dubbo() {
ProtocolConfig protocolConfig = new ProtocolConfig("dubbo");
return protocolConfig;
}
// expose services with tri protocol
@Bean
public ProtocolConfig tri() {
ProtocolConfig protocolConfig = new ProtocolConfig("tri");
return protocolConfig;
}
// customized thread pool
@Bean("executor-demo-service")
public Executor demoServiceExecutor() {
return new DemoServiceExecutor();
}
// customized thread pool
@Bean("executor-hello-service")
public Executor helloServiceExecutor() {
return new HelloServiceExecutor();
}
}
}
| 8,685 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.provider;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@DubboService(version = "3.0.0", group = "Group3")
public class HelloServiceImplV2 implements HelloService {
private static final Logger logger = LoggerFactory.getLogger(HelloServiceImplV2.class);
@Override
public String sayHello(String name) {
return "server hello";
}
}
| 8,686 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/HelloServiceImplV3.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.provider;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@DubboService(executor = "executor-hello-service", version = "2.0.0", group = "Group2")
public class HelloServiceImplV3 implements HelloService {
private static final Logger logger = LoggerFactory.getLogger(HelloServiceImplV3.class);
@Override
public String sayHello(String name) {
return "server hello";
}
}
| 8,687 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/provider/DemoServiceImplV1.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.provider;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
@DubboService(executor = "executor-demo-service", version = "1.0.0", group = "Group1")
public class DemoServiceImplV1 implements DemoService {
@Override
public String sayName(String name) {
return "server name";
}
@Override
public Box getBox() {
return null;
}
}
| 8,688 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV3.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.tri;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.stereotype.Component;
@Component("tri-helloServiceV3")
public class HelloServiceV3 implements HelloService {
@DubboReference(version = "3.0.0", group = "Group3", scope = "remote", protocol = "tri")
private HelloService helloService;
@Override
public String sayHello(String name) {
return helloService.sayHello(name);
}
}
| 8,689 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/HelloServiceV2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.tri;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.stereotype.Component;
@Component("tri-helloServiceV2")
public class HelloServiceV2 implements HelloService {
@DubboReference(version = "2.0.0", group = "Group2", scope = "remote", protocol = "tri")
private HelloService helloService;
@Override
public String sayHello(String name) {
return helloService.sayHello(name);
}
}
| 8,690 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/tri/DemoServiceV1.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.tri;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
import org.springframework.stereotype.Component;
@Component("tri-demoServiceV1")
public class DemoServiceV1 implements DemoService {
@DubboReference(version = "1.0.0", group = "Group1", scope = "remote", protocol = "tri")
private DemoService demoService;
@Override
public String sayName(String name) {
return demoService.sayName(name);
}
@Override
public Box getBox() {
return null;
}
}
| 8,691 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV3.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.dubbo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.stereotype.Component;
@Component("dubbo-helloServiceV3")
public class HelloServiceV3 implements HelloService {
@DubboReference(version = "3.0.0", group = "Group3", scope = "remote", protocol = "dubbo")
private HelloService helloService;
@Override
public String sayHello(String name) {
return helloService.sayHello(name);
}
}
| 8,692 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.dubbo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.stereotype.Component;
@Component("dubbo-helloServiceV2")
public class HelloServiceV2 implements HelloService {
@DubboReference(version = "2.0.0", group = "Group2", scope = "remote", protocol = "dubbo")
private HelloService helloService;
@Override
public String sayHello(String name) {
return helloService.sayHello(name);
}
}
| 8,693 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/DemoServiceV1.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.annotation.consumer.dubbo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.api.Box;
import org.apache.dubbo.config.spring.api.DemoService;
import org.springframework.stereotype.Component;
@Component("dubbo-demoServiceV1")
public class DemoServiceV1 implements DemoService {
@DubboReference(version = "1.0.0", group = "Group1", scope = "remote", protocol = "dubbo")
private DemoService demoService;
@Override
public String sayName(String name) {
return demoService.sayName(name);
}
@Override
public Box getBox() {
return null;
}
}
| 8,694 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/xml/XmlIsolationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.xml;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.spring.isolation.spring.BaseTest;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlIsolationTest extends BaseTest {
@Test
public void test() throws Exception {
// start provider app
ClassPathXmlApplicationContext providerContext =
new ClassPathXmlApplicationContext("META-INF/isolation/dubbo-provider.xml");
providerContext.start();
// start consumer app
ClassPathXmlApplicationContext consumerContext =
new ClassPathXmlApplicationContext("META-INF/isolation/dubbo-consumer.xml");
consumerContext.start();
// getAndSet serviceConfig
setServiceConfig(providerContext);
// assert isolation of executor
assertExecutor(providerContext, consumerContext);
// close context
providerContext.close();
consumerContext.close();
}
private void setServiceConfig(ClassPathXmlApplicationContext providerContext) {
Map<String, ServiceConfig> serviceConfigMap = providerContext.getBeansOfType(ServiceConfig.class);
serviceConfig1 = serviceConfigMap.get("org.apache.dubbo.config.spring.ServiceBean#0");
serviceConfig2 = serviceConfigMap.get("org.apache.dubbo.config.spring.ServiceBean#1");
serviceConfig3 = serviceConfigMap.get("org.apache.dubbo.config.spring.ServiceBean#2");
}
}
| 8,695 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/HelloServiceExecutor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.support;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HelloServiceExecutor extends ThreadPoolExecutor {
public HelloServiceExecutor() {
super(
100,
100,
60,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(),
new NamedThreadFactory("HelloServiceExecutor"));
}
}
| 8,696 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/support/DemoServiceExecutor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.isolation.spring.support;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class DemoServiceExecutor extends ThreadPoolExecutor {
public DemoServiceExecutor() {
super(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new NamedThreadFactory("DemoServiceExecutor"));
}
}
| 8,697 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessorTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.beans.factory.config;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
class DubboConfigDefaultPropertyValueBeanPostProcessorTest {
@Test
void test() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ProviderConfiguration.class);
try {
context.start();
ApplicationConfig applicationConfig = context.getBean(ApplicationConfig.class);
Assertions.assertEquals(applicationConfig.getName(), applicationConfig.getId());
ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class);
Assertions.assertEquals(protocolConfig.getName(), protocolConfig.getId());
} finally {
context.close();
}
}
}
| 8,698 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactoryTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.spring.beans.factory.config;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
/**
* {@link YamlPropertySourceFactory} Test
*
* @since 2.6.5
*/
@ExtendWith(SpringExtension.class)
@PropertySource(
name = "yaml-source",
value = {"classpath:/META-INF/dubbo.yml"},
factory = YamlPropertySourceFactory.class)
@Configuration
@ContextConfiguration(classes = YamlPropertySourceFactoryTest.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
class YamlPropertySourceFactoryTest {
@Autowired
private Environment environment;
@Value("${dubbo.consumer.default}")
private Boolean isDefault;
@Value("${dubbo.consumer.client}")
private String client;
@Value("${dubbo.consumer.threadpool}")
private String threadPool;
@Value("${dubbo.consumer.corethreads}")
private Integer coreThreads;
@Value("${dubbo.consumer.threads}")
private Integer threads;
@Value("${dubbo.consumer.queues}")
private Integer queues;
@Test
void testProperty() {
Assertions.assertEquals(isDefault, environment.getProperty("dubbo.consumer.default", Boolean.class));
Assertions.assertEquals(client, environment.getProperty("dubbo.consumer.client", String.class));
Assertions.assertEquals(threadPool, environment.getProperty("dubbo.consumer.threadpool", String.class));
Assertions.assertEquals(coreThreads, environment.getProperty("dubbo.consumer.corethreads", Integer.class));
Assertions.assertEquals(threads, environment.getProperty("dubbo.consumer.threads", Integer.class));
Assertions.assertEquals(queues, environment.getProperty("dubbo.consumer.queues", Integer.class));
}
}
| 8,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.