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/test/java/org/apache/dubbo/config/integration/multiple
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.multiple.exportmetadata;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener;
import org.apache.dubbo.metadata.MetadataService;
/**
* This implementation of {@link ServiceListener} is to record exported metadata services in multiple registry center.
*/
public class MultipleRegistryCenterExportMetadataServiceListener extends AbstractRegistryCenterServiceListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return MetadataService.class;
}
}
| 8,500 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.multiple.exportmetadata;
/**
* This interface is used to check if the exported metadata service works well or not in multiple registry center.
*/
public interface MultipleRegistryCenterExportMetadataService {
/**
* The simple method for testing.
*/
String hello(String name);
}
| 8,501 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.multiple.exportmetadata;
/**
* The simple implementation for {@link MultipleRegistryCenterExportMetadataService}
*/
public class MultipleRegistryCenterExportMetadataServiceImpl implements MultipleRegistryCenterExportMetadataService {
/**
* {@inheritDoc}
*/
@Override
public String hello(String name) {
return "Hello " + name;
}
}
| 8,502 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterIntegrationServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The implementation for {@link SingleRegistryCenterIntegrationService}
*/
public class SingleRegistryCenterIntegrationServiceImpl implements SingleRegistryCenterIntegrationService {
private static final Logger logger = LoggerFactory.getLogger(SingleRegistryCenterIntegrationServiceImpl.class);
@Override
public String hello(String name) {
String value = "Hello " + name;
logger.info(value);
return value;
}
}
| 8,503 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterExportedServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener;
/**
* This implementation of {@link ServiceListener} is to record exported services in single registry center.
*/
public class SingleRegistryCenterExportedServiceListener extends AbstractRegistryCenterServiceListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return SingleRegistryCenterIntegrationService.class;
}
}
| 8,504 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterIntegrationService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single;
/**
* This interface for integration testcases in single registry center.
*/
public interface SingleRegistryCenterIntegrationService {
String hello(String name);
}
| 8,505 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/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.
*/
/**
* There are two scenario in integration testcases.<p>
* The one is single registry center, the other is multiple registry centers.<p>
* The purpose of all of testcases in this package is to test for single registry center.
*/
package org.apache.dubbo.config.integration.single;
| 8,506 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/SingleRegistryCenterDubboProtocolIntegrationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.integration.IntegrationTest;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.ListenerRegistryWrapper;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry;
import org.apache.dubbo.registry.client.ServiceDiscoveryRegistryDirectory;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.registry.zookeeper.ZookeeperServiceDiscovery;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
/**
* This abstraction class will implement some methods as base for single registry center.
*/
@DisabledForJreRange(min = JRE.JAVA_16)
class SingleRegistryCenterDubboProtocolIntegrationTest implements IntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(SingleRegistryCenterDubboProtocolIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "single-registry-center-provider-for-dubbo-protocol";
/**
* Define the protocol's name.
*/
private static String PROTOCOL_NAME = CommonConstants.DUBBO;
/**
* Define the protocol's port.
*/
private static int PROTOCOL_PORT = 20800;
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<SingleRegistryCenterIntegrationServiceImpl> serviceConfig;
/**
* Define the {@link ReferenceConfig} instance.
*/
private ReferenceConfig<SingleRegistryCenterIntegrationService> referenceConfig;
/**
* Define the {@link RegistryConfig} instance.
*/
private RegistryConfig registryConfig;
/**
* The service instance of {@link SingleRegistryCenterIntegrationService}
*/
private SingleRegistryCenterIntegrationService singleRegistryCenterIntegrationService;
/**
* Define the {@link SingleRegistryCenterExportedServiceListener} instance to obtain the exported services.
*/
private SingleRegistryCenterExportedServiceListener singleRegistryCenterExportedServiceListener;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize ServiceConfig
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(SingleRegistryCenterIntegrationService.class);
serviceConfig.setRef(new SingleRegistryCenterIntegrationServiceImpl());
serviceConfig.setAsync(false);
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT))
.service(serviceConfig);
registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress());
DubboBootstrap.getInstance().registry(registryConfig);
}
@Test
@Override
public void integrate() {
this.beforeExport();
// export provider
DubboBootstrap.getInstance().start();
this.afterExport();
// initialize consumer
this.initConsumer();
this.beforeRefer();
singleRegistryCenterIntegrationService = referenceConfig.get();
this.afterRefer();
}
/**
* There are some checkpoints needed to check as follow :
* <ul>
* <li>ServiceConfig is exported or not</li>
* <li>ServiceConfig's exportedUrl has values or not</li>
* <li>DubboBootstrap is initialized or not</li>
* <li>DubboBootstrap is started or not</li>
* <li>DubboBootstrap is shutdown or not</li>
* <li>The ServiceListener is loaded by SPI or not</li>
* </ul>
*/
private void beforeExport() {
// ServiceConfig is exported or not
Assertions.assertFalse(serviceConfig.isExported());
// ServiceConfig's exportedUrl has values or not
Assertions.assertEquals(serviceConfig.getExportedUrls().size(), 0);
// DubboBootstrap is pending or not
Assertions.assertTrue(DubboBootstrap.getInstance().isPending());
// DubboBootstrap is initialized or not
Assertions.assertFalse(DubboBootstrap.getInstance().isInitialized());
// DubboBootstrap is started or not
Assertions.assertFalse(DubboBootstrap.getInstance().isStarted());
// DubboBootstrap is stopped or not
Assertions.assertFalse(DubboBootstrap.getInstance().isStopped());
// The ServiceListener is loaded by SPI or not
Assertions.assertNull(singleRegistryCenterExportedServiceListener);
}
/**
* There are some checkpoints needed to check as follow :
* <ul>
* <li>DubboBootstrap is initialized or not</li>
* <li>DubboBootstrap is started or not</li>
* <li>DubboBootstrap is shutdown or not</li>
* <li>Service has been exported or not</li>
* <li>There is exported urls or not</li>
* <li>Protocol name is right or not</li>
* <li>Protocol port is right or not</li>
* <li>ServiceDiscoveryRegistry's protocol is right or not</li>
* <li>Registered service in registry center is right or not</li>
* <li>MetadataInfo has reported or not</li>
* <li>MetadataInfo has reported or not has service or not</li>
* <li>MetadataInfo's application name is right or not</li>
* <li>MetadataInfo's service exists or not</li>
* <li>The name of MetadataInfo's service is right or not</li>
* <li>The group of MetadataInfo's service is right or not</li>
* <li>The version of MetadataInfo's service is right or not</li>
* <li>The protocol of MetadataInfo's service is right or not</li>
* <li>The serviceKey of MetadataInfo's service is right or not</li>
* <li>The matchKey of MetadataInfo's service is right or not</li>
* <li>The exported service are right or not</li>
* </ul>
*/
private void afterExport() {
// DubboBootstrap is initialized or not
Assertions.assertTrue(DubboBootstrap.getInstance().isInitialized());
// DubboBootstrap is pending or not
Assertions.assertFalse(DubboBootstrap.getInstance().isPending());
// DubboBootstrap is started or not
Assertions.assertTrue(DubboBootstrap.getInstance().isStarted());
// DubboBootstrap is shutdown or not
Assertions.assertFalse(DubboBootstrap.getInstance().isStopped());
// Service has been exported or not
Assertions.assertTrue(this.serviceConfig.isExported());
// There is exported urls or not
Assertions.assertEquals(this.serviceConfig.getExportedUrls().size(), 1);
URL exportedUrl = this.serviceConfig.getExportedUrls().get(0);
// Protocol name is right or not
Assertions.assertEquals(exportedUrl.getProtocol(), PROTOCOL_NAME);
// Protocol port is right or not
Assertions.assertEquals(exportedUrl.getPort(), PROTOCOL_PORT);
// Application name is right or not
Assertions.assertEquals(exportedUrl.getApplication(), PROVIDER_APPLICATION_NAME);
// obtain ServiceDiscoveryRegistry instance
ServiceDiscoveryRegistry serviceDiscoveryRegistry = this.getServiceDiscoveryRegistry();
// ServiceDiscoveryRegistry instance cannot be null
Assertions.assertNotNull(serviceDiscoveryRegistry);
// ServiceDiscoveryRegistry's protocol is right or not
Assertions.assertTrue(serviceDiscoveryRegistry.getServiceDiscovery() instanceof ZookeeperServiceDiscovery);
// Convert to ZookeeperServiceDiscovery instance
ZookeeperServiceDiscovery zookeeperServiceDiscovery =
(ZookeeperServiceDiscovery) serviceDiscoveryRegistry.getServiceDiscovery();
// Gets registered service by ZookeeperServiceDiscovery
Set<String> services = zookeeperServiceDiscovery.getServices();
// check service exists
Assertions.assertTrue(!services.isEmpty());
// Registered service in registry center is right or not
Assertions.assertTrue(services.contains(PROVIDER_APPLICATION_NAME));
// obtain InMemoryWritableMetadataService instance
MetadataServiceDelegation inMemoryWritableMetadataService = (MetadataServiceDelegation)
serviceConfig.getScopeModel().getBeanFactory().getBean(MetadataService.class);
// Exported url is right or not in InMemoryWritableMetadataService
Assertions.assertEquals(
inMemoryWritableMetadataService.getExportedURLs().size(), 1);
// MetadataInfo exists or not in InMemoryWritableMetadataService
Assertions.assertFalse(
inMemoryWritableMetadataService.getMetadataInfos().isEmpty());
// MetadataInfo has reported or not has service or not
Assertions.assertFalse(inMemoryWritableMetadataService
.getMetadataInfos()
.get(0)
.getServices()
.isEmpty());
// MetadataInfo has reported or not has service or not
Assertions.assertEquals(
inMemoryWritableMetadataService
.getMetadataInfos()
.get(0)
.getServices()
.size(),
1);
// obtain the service's key
String key = SingleRegistryCenterIntegrationService.class.getName() + ":" + PROTOCOL_NAME;
MetadataInfo.ServiceInfo serviceInfo = inMemoryWritableMetadataService
.getMetadataInfos()
.get(0)
.getServices()
.get(key);
// MetadataInfo's service exists or not
Assertions.assertNotNull(serviceInfo);
// The name of MetadataInfo's service is right or not
Assertions.assertEquals(serviceInfo.getName(), SingleRegistryCenterIntegrationService.class.getName());
// The group of MetadataInfo's service is right or not
Assertions.assertNull(serviceInfo.getGroup());
// The version of MetadataInfo's service is right or not
Assertions.assertNull(serviceInfo.getVersion());
// The protocol of MetadataInfo's service is right or not
Assertions.assertEquals(serviceInfo.getProtocol(), PROTOCOL_NAME);
// The serviceKey of MetadataInfo's service is right or not
Assertions.assertEquals(serviceInfo.getServiceKey(), SingleRegistryCenterIntegrationService.class.getName());
// The matchKey of MetadataInfo's service is right or not
Assertions.assertEquals(serviceInfo.getMatchKey(), key);
// The exported services are right or not
// 1. The exported service must contain SingleRegistryCenterIntegrationService
// 2. The exported service's interface must be SingleRegistryCenterIntegrationService.class
// 3. All exported services must be exported
singleRegistryCenterExportedServiceListener = (SingleRegistryCenterExportedServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension("exported");
Assertions.assertNotNull(singleRegistryCenterExportedServiceListener);
Assertions.assertEquals(
singleRegistryCenterExportedServiceListener
.getExportedServices()
.size(),
1);
Assertions.assertEquals(
SingleRegistryCenterIntegrationService.class,
singleRegistryCenterExportedServiceListener
.getExportedServices()
.get(0)
.getInterfaceClass());
ServiceConfig singleRegistryCenterServiceConfig = singleRegistryCenterExportedServiceListener
.getExportedServices()
.get(0);
Assertions.assertNotNull(singleRegistryCenterServiceConfig);
Assertions.assertTrue(singleRegistryCenterServiceConfig.isExported());
}
/**
* Returns {@link ServiceDiscoveryRegistry} instance.
* <p>
* FIXME It's not a good way to obtain {@link ServiceDiscoveryRegistry} using Reflection.
*/
private ServiceDiscoveryRegistry getServiceDiscoveryRegistry() {
Collection<Registry> registries =
RegistryManager.getInstance(ApplicationModel.defaultModel()).getRegistries();
for (Registry registry : registries) {
if (registry instanceof ServiceDiscoveryRegistry) {
return (ServiceDiscoveryRegistry) registry;
}
}
return null;
}
/**
* Initialize the consumer.
*/
private void initConsumer() {
referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(SingleRegistryCenterIntegrationService.class);
DubboBootstrap.getInstance().reference(referenceConfig);
referenceConfig.setRegistry(registryConfig);
referenceConfig.setScope(SCOPE_REMOTE);
referenceConfig.setGeneric("false");
referenceConfig.setProtocol(PROTOCOL_NAME);
}
/**
* There are some checkpoints needed to check before referring as follow :
* <ul>
* <li>ReferenceConfig has integrated into DubboBootstrap or not</li>
* </ul>
*/
private void beforeRefer() {
// ReferenceConfig has integrated into DubboBootstrap or not
Assertions.assertEquals(
referenceConfig.getScopeModel(),
DubboBootstrap.getInstance().getApplicationModel().getDefaultModule());
}
/**
* There are some checkpoints needed to check after referred as follow :
* <ul>
* <li>SingleRegistryCenterIntegrationService instance can't be null</li>
* <li>RPC works well or not</li>
* <li>Invoker is right or not</li>
* <li>Directory is null or not</li>
* <li>Registered interface is right or not</li>
* <li>Directory is available or not</li>
* <li>Directory is destroyed or not</li>
* <li>Directory has received notification or not</li>
* <li>ServiceDiscoveryRegistryDirectory should register or not</li>
* <li>ServiceDiscoveryRegistryDirectory's registered consumer url is right or not</li>
* <li>ServiceDiscoveryRegistryDirectory's registry is right or not</li>
* <li>Directory's invokers are right or not</li>
* </ul>
*/
private void afterRefer() {
// SingleRegistryCenterIntegrationService instance can't be null
Assertions.assertNotNull(singleRegistryCenterIntegrationService);
// Invoker is right or not
Assertions.assertNotNull(referenceConfig.getInvoker());
Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker);
// RPC works well or not
Assertions.assertEquals("Hello Reference", singleRegistryCenterIntegrationService.hello("Reference"));
// get ServiceDiscoveryRegistryDirectory instance
Directory directory = ((MigrationInvoker) referenceConfig.getInvoker()).getDirectory();
// Directory is null or not
Assertions.assertNotNull(directory);
// Check Directory's type
Assertions.assertTrue(directory instanceof ServiceDiscoveryRegistryDirectory);
// Registered interface is right or not
Assertions.assertEquals(directory.getInterface(), SingleRegistryCenterIntegrationService.class);
// Directory is available or not
Assertions.assertTrue(directory.isAvailable());
// Directory is destroyed or not
Assertions.assertFalse(directory.isDestroyed());
// Directory has received notification or not
Assertions.assertTrue(directory.isNotificationReceived());
ServiceDiscoveryRegistryDirectory serviceDiscoveryRegistryDirectory =
(ServiceDiscoveryRegistryDirectory) directory;
// ServiceDiscoveryRegistryDirectory should register or not
Assertions.assertTrue(serviceDiscoveryRegistryDirectory.isShouldRegister());
// ServiceDiscoveryRegistryDirectory's registered consumer url is right or not
Assertions.assertEquals(
serviceDiscoveryRegistryDirectory.getRegisteredConsumerUrl().getCategory(), CONSUMERS_CATEGORY);
// ServiceDiscoveryRegistryDirectory's registry is right or not
Assertions.assertTrue(serviceDiscoveryRegistryDirectory.getRegistry() instanceof ListenerRegistryWrapper);
// Directory's invokers are right or not
Assertions.assertEquals(
serviceDiscoveryRegistryDirectory.getAllInvokers().size(), 1);
Assertions.assertEquals(
serviceDiscoveryRegistryDirectory.getInvokers(), serviceDiscoveryRegistryDirectory.getAllInvokers());
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
PROVIDER_APPLICATION_NAME = null;
PROTOCOL_NAME = null;
PROTOCOL_PORT = 0;
serviceConfig = null;
referenceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(singleRegistryCenterExportedServiceListener
.getExportedServices()
.isEmpty());
singleRegistryCenterExportedServiceListener = null;
logger.info(getClass().getSimpleName() + " testcase is ending...");
}
}
| 8,507 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.injvm;
/**
* This interface is used to check if the exported injvm protocol works well or not.
*/
public interface SingleRegistryCenterInjvmService {
/**
* The simple method for testing.
*/
String hello(String name);
}
| 8,508 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmIntegrationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.injvm;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.integration.IntegrationTest;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
/**
* The testcases are only for checking the process of exporting provider using injvm protocol.
*/
class SingleRegistryCenterInjvmIntegrationTest implements IntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(SingleRegistryCenterInjvmIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "single-registry-center-provider-for-injvm-protocol";
/**
* The name for getting the specified instance, which is loaded using SPI.
*/
private static String SPI_NAME = "singleConfigCenterInjvm";
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<SingleRegistryCenterInjvmService> serviceConfig;
/**
* The listener to record exported services
*/
private SingleRegistryCenterInjvmServiceListener serviceListener;
/**
* The listener to record exported exporters.
*/
private SingleRegistryCenterInjvmExporterListener exporterListener;
/**
* The filter for checking filter chain.
*/
private SingleRegistryCenterInjvmFilter filter;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize service config
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(SingleRegistryCenterInjvmService.class);
serviceConfig.setRef(new SingleRegistryCenterInjvmServiceImpl());
serviceConfig.setAsync(false);
serviceConfig.setScope(SCOPE_LOCAL);
// initailize bootstrap
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig("injvm"))
.service(serviceConfig);
RegistryConfig registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress());
DubboBootstrap.getInstance().registry(registryConfig);
}
/**
* Define {@link ServiceListener}, {@link ExporterListener} and {@link Filter} for helping check.
* <p>Use SPI to load them before exporting.
* <p>After that, there are some checkpoints need to verify as follow:
* <ul>
* <li>There is nothing in ServiceListener or not</li>
* <li>There is nothing in ExporterListener or not</li>
* <li>ServiceConfig is exported or not</li>
* </ul>
*/
private void beforeExport() {
// ---------------initialize--------------- //
serviceListener = (SingleRegistryCenterInjvmServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME);
exporterListener = (SingleRegistryCenterInjvmExporterListener)
ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME);
filter = (SingleRegistryCenterInjvmFilter)
ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME);
// ---------------checkpoints--------------- //
// There is nothing in ServiceListener
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
// There is nothing in ExporterListener
Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty());
// ServiceConfig isn't exported
Assertions.assertFalse(serviceConfig.isExported());
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void integrate() {
beforeExport();
DubboBootstrap.getInstance().start();
afterExport();
ReferenceConfig<SingleRegistryCenterInjvmService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(SingleRegistryCenterInjvmService.class);
referenceConfig.setScope(SCOPE_LOCAL);
referenceConfig.get().hello("Dubbo");
afterInvoke();
}
/**
* There are some checkpoints need to check after exported as follow:
* <ul>
* <li>The exported service is only one or not</li>
* <li>The exported service is SingleRegistryCenterInjvmService or not</li>
* <li>The SingleRegistryCenterInjvmService is exported or not</li>
* <li>The exported exporter is only one or not</li>
* <li>The exported exporter contains SingleRegistryCenterInjvmFilter or not</li>
* </ul>
*/
private void afterExport() {
// The exported service is only one
Assertions.assertEquals(serviceListener.getExportedServices().size(), 1);
// The exported service is SingleRegistryCenterInjvmService
Assertions.assertEquals(
serviceListener.getExportedServices().get(0).getInterfaceClass(),
SingleRegistryCenterInjvmService.class);
// The SingleRegistryCenterInjvmService is exported
Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported());
// The exported exporter is only one
Assertions.assertEquals(exporterListener.getExportedExporters().size(), 3);
// The exported exporter contains SingleRegistryCenterInjvmFilter
Assertions.assertTrue(exporterListener.getFilters().contains(filter));
}
/**
* There are some checkpoints need to check after invoked as follow:
* <ul>
* <li>The SingleRegistryCenterInjvmFilter has called or not</li>
* <li>The SingleRegistryCenterInjvmFilter exists error after invoked</li>
* <li>The SingleRegistryCenterInjvmFilter's response is right or not</li>
* </ul>
*/
private void afterInvoke() {
// The SingleRegistryCenterInjvmFilter has called
Assertions.assertTrue(filter.hasCalled());
// The SingleRegistryCenterInjvmFilter doesn't exist error
Assertions.assertFalse(filter.hasError());
// Check the SingleRegistryCenterInjvmFilter's response
Assertions.assertEquals("Hello Dubbo", filter.getResponse());
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
PROVIDER_APPLICATION_NAME = null;
serviceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
serviceListener = null;
logger.info(getClass().getSimpleName() + " testcase is ending...");
}
}
| 8,509 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.injvm;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener;
/**
* This implementation of {@link ServiceListener} is to record exported services with injvm protocol in single registry center.
*/
public class SingleRegistryCenterInjvmServiceListener extends AbstractRegistryCenterServiceListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return SingleRegistryCenterInjvmService.class;
}
}
| 8,510 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmExporterListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.injvm;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener;
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class SingleRegistryCenterInjvmExporterListener extends AbstractRegistryCenterExporterListener {
/**
* Returns the interface of exported service.
*/
@Override
protected Class<?> getInterface() {
return SingleRegistryCenterInjvmService.class;
}
}
| 8,511 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.injvm;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
@Activate(group = CommonConstants.PROVIDER, order = 10000)
public class SingleRegistryCenterInjvmFilter implements Filter, Filter.Listener {
/**
* The filter is called or not
*/
private boolean called = false;
/**
* There has error after invoked
*/
private boolean error = false;
/**
* The returned result
*/
private String response;
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*
* @param invoker
* @param invocation
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
called = true;
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
response = String.valueOf(appResponse.getValue());
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
error = true;
}
/**
* Returns if the filter has called.
*/
public boolean hasCalled() {
return called;
}
/**
* Returns if there exists error.
*/
public boolean hasError() {
return error;
}
/**
* Returns the response.
*/
public String getResponse() {
return response;
}
}
| 8,512 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.injvm;
/**
* The simple implementation for {@link SingleRegistryCenterInjvmService}
*/
public class SingleRegistryCenterInjvmServiceImpl implements SingleRegistryCenterInjvmService {
/**
* {@inheritDoc}
*/
@Override
public String hello(String name) {
return "Hello " + name;
}
}
| 8,513 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderExporterListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener;
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class SingleRegistryCenterExportProviderExporterListener extends AbstractRegistryCenterExporterListener {
/**
* Returns the interface of exported service.
*/
@Override
protected Class<?> getInterface() {
return SingleRegistryCenterExportProviderService.class;
}
}
| 8,514 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
/**
* This interface is used to check if the exported provider works well or not.
*/
public interface SingleRegistryCenterExportProviderService {
/**
* The simple method for testing.
*/
String hello(String name);
}
| 8,515 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderRegistryProtocolListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.registry.integration.RegistryProtocolListener;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import static org.apache.dubbo.config.integration.Constants.SINGLE_CONFIG_CENTER_EXPORT_PROVIDER;
/**
* The {@link RegistryProtocolListener} for {@link SingleRegistryCenterExportProviderService}
*/
@Activate(order = 100, value = SINGLE_CONFIG_CENTER_EXPORT_PROVIDER)
public class SingleRegistryCenterExportProviderRegistryProtocolListener implements RegistryProtocolListener {
private boolean exported = false;
/**
* {@inheritDoc}
*/
@Override
public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {
if (registryProtocol instanceof InterfaceCompatibleRegistryProtocol
&& exporter != null
&& exporter.getInvoker() != null
&& exporter.getInvoker().getInterface().equals(SingleRegistryCenterExportProviderService.class)) {
this.exported = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL) {}
/**
* {@inheritDoc}
*/
@Override
public void onDestroy() {}
/**
* Returns if this exporter is exported.
*/
public boolean isExported() {
return exported;
}
}
| 8,516 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener;
/**
* This implementation of {@link ServiceListener} is to record exported services with injvm protocol in single registry center.
*/
public class SingleRegistryCenterExportProviderServiceListener extends AbstractRegistryCenterServiceListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return SingleRegistryCenterExportProviderService.class;
}
}
| 8,517 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
/**
* The implementation of {@link SingleRegistryCenterExportProviderService}
*/
public class SingleRegistryCenterExportProviderServiceImpl implements SingleRegistryCenterExportProviderService {
/**
* {@inheritDoc}
*/
@Override
public String hello(String name) {
return "Hello " + name;
}
}
| 8,518 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
@Activate(group = CommonConstants.PROVIDER, order = 10000)
public class SingleRegistryCenterExportProviderFilter implements Filter, Filter.Listener {
/**
* The filter is called or not
*/
private boolean called = false;
/**
* There has error after invoked
*/
private boolean error = false;
/**
* The returned result
*/
private String response;
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*
* @param invoker
* @param invocation
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
called = true;
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
response = String.valueOf(appResponse.getValue());
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
error = true;
}
/**
* Returns if the filter has called.
*/
public boolean hasCalled() {
return called;
}
/**
* Returns if there exists error.
*/
public boolean hasError() {
return error;
}
/**
* Returns the response.
*/
public String getResponse() {
return response;
}
}
| 8,519 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportprovider/SingleRegistryCenterExportProviderIntegrationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportprovider;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.integration.IntegrationTest;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.registry.integration.RegistryProtocolListener;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.io.IOException;
import java.util.HashMap;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_PROTOCOL_LISTENER_KEY;
import static org.apache.dubbo.config.integration.Constants.SINGLE_CONFIG_CENTER_EXPORT_PROVIDER;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
/**
* The testcases are only for checking the core process of exporting provider.
*/
class SingleRegistryCenterExportProviderIntegrationTest implements IntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(SingleRegistryCenterExportProviderIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "single-registry-center-for-export-provider";
/**
* Define the protocol's name.
*/
private static String PROTOCOL_NAME = CommonConstants.DUBBO;
/**
* Define the protocol's port.
*/
private static int PROTOCOL_PORT = 20800;
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<SingleRegistryCenterExportProviderService> serviceConfig;
/**
* Define a {@link RegistryProtocolListener} instance.
*/
private SingleRegistryCenterExportProviderRegistryProtocolListener registryProtocolListener;
/**
* Define a {@link ExporterListener} instance.
*/
private SingleRegistryCenterExportProviderExporterListener exporterListener;
/**
* Define a {@link Filter} instance.
*/
private SingleRegistryCenterExportProviderFilter filter;
/**
* Define a {@link ServiceListener} instance.
*/
private SingleRegistryCenterExportProviderServiceListener serviceListener;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize service config
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(SingleRegistryCenterExportProviderService.class);
serviceConfig.setRef(new SingleRegistryCenterExportProviderServiceImpl());
serviceConfig.setAsync(false);
// initialize bootstrap
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT))
.service(serviceConfig);
RegistryConfig registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress());
Map<String, String> parameters = new HashMap<>();
parameters.put(REGISTRY_PROTOCOL_LISTENER_KEY, "singleConfigCenterExportProvider");
registryConfig.updateParameters(parameters);
DubboBootstrap.getInstance().registry(registryConfig);
}
/**
* There are some checkpoints need to verify as follow:
* <ul>
* <li>ServiceConfig is exported or not</li>
* <li>SingleRegistryCenterExportProviderRegistryProtocolListener is null or not</li>
* <li>There is nothing in ServiceListener or not</li>
* <li>There is nothing in ExporterListener or not</li>
* </ul>
*/
private void beforeExport() {
registryProtocolListener = (SingleRegistryCenterExportProviderRegistryProtocolListener)
ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)
.getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER);
exporterListener = (SingleRegistryCenterExportProviderExporterListener)
ExtensionLoader.getExtensionLoader(ExporterListener.class)
.getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER);
filter = (SingleRegistryCenterExportProviderFilter)
ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER);
serviceListener = (SingleRegistryCenterExportProviderServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class)
.getExtension(SINGLE_CONFIG_CENTER_EXPORT_PROVIDER);
// ---------------checkpoints--------------- //
// ServiceConfig isn't exported
Assertions.assertFalse(serviceConfig.isExported());
// registryProtocolListener is just initialized by SPI
// so, all of fields are the default value.
Assertions.assertNotNull(registryProtocolListener);
Assertions.assertFalse(registryProtocolListener.isExported());
// There is nothing in ServiceListener
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
// There is nothing in ExporterListener
Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty());
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void integrate() {
beforeExport();
DubboBootstrap.getInstance().start();
afterExport();
ReferenceConfig<SingleRegistryCenterExportProviderService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(SingleRegistryCenterExportProviderService.class);
referenceConfig.setScope(SCOPE_LOCAL);
referenceConfig.get().hello(PROVIDER_APPLICATION_NAME);
afterInvoke();
}
/**
* There are some checkpoints need to check after exported as follow:
* <ul>
* <li>the exporter is exported or not</li>
* <li>The exported exporter are three</li>
* <li>The exported service is SingleRegistryCenterExportProviderService or not</li>
* <li>The SingleRegistryCenterExportProviderService is exported or not</li>
* <li>The exported exporter contains SingleRegistryCenterExportProviderFilter or not</li>
* <li>The metadata mapping info is right or not</li>
* </ul>
*/
private void afterExport() {
// The exporter is exported
Assertions.assertTrue(registryProtocolListener.isExported());
// The exported service is only one
Assertions.assertEquals(serviceListener.getExportedServices().size(), 1);
// The exported service is SingleRegistryCenterExportProviderService
Assertions.assertEquals(
serviceListener.getExportedServices().get(0).getInterfaceClass(),
SingleRegistryCenterExportProviderService.class);
// The SingleRegistryCenterExportProviderService is exported
Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported());
// The exported exporter are three
// 1. InjvmExporter
// 2. DubboExporter with service-discovery-registry protocol
// 3. DubboExporter with registry protocol
Assertions.assertEquals(exporterListener.getExportedExporters().size(), 4);
// The exported exporter contains SingleRegistryCenterExportProviderFilter
Assertions.assertTrue(exporterListener.getFilters().contains(filter));
// The consumer can be notified and get provider's metadata through metadata mapping info.
// So, the metadata mapping is necessary to check after exported service (or provider)
// The best way to verify this issue is to check if the exported service (or provider)
// has been registered in the path of /dubbo/mapping/****
// What are the parameters?
// registryKey: the registryKey is the default cluster, CommonConstants.DEFAULT_KEY
// key: The exported interface's name
// group: the group is "mapping", ServiceNameMapping.DEFAULT_MAPPING_GROUP
ConfigItem configItem = ApplicationModel.defaultModel()
.getBeanFactory()
.getBean(MetadataReportInstance.class)
.getMetadataReport(CommonConstants.DEFAULT_KEY)
.getConfigItem(serviceConfig.getInterface(), ServiceNameMapping.DEFAULT_MAPPING_GROUP);
// Check if the exported service (provider) is registered
Assertions.assertNotNull(configItem);
// Check if registered service (provider)'s name is right
Assertions.assertEquals(PROVIDER_APPLICATION_NAME, configItem.getContent());
// Check if registered service (provider)'s version exists
Assertions.assertNotNull(configItem.getTicket());
}
/**
* There are some checkpoints need to check after invoked as follow:
* <ul>
* <li>The SingleRegistryCenterExportProviderFilter has called or not</li>
* <li>The SingleRegistryCenterExportProviderFilter exists error after invoked</li>
* <li>The SingleRegistryCenterExportProviderFilter's response is right or not</li>
* </ul>
*/
private void afterInvoke() {
// The SingleRegistryCenterExportProviderFilter has called
Assertions.assertTrue(filter.hasCalled());
// The SingleRegistryCenterExportProviderFilter doesn't exist error
Assertions.assertFalse(filter.hasError());
// Check the SingleRegistryCenterExportProviderFilter's response
Assertions.assertEquals("Hello " + PROVIDER_APPLICATION_NAME, filter.getResponse());
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
PROVIDER_APPLICATION_NAME = null;
serviceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
logger.info(getClass().getSimpleName() + " testcase is ending...");
registryProtocolListener = null;
}
}
| 8,520 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportmetadata;
/**
* The simple implementation for {@link SingleRegistryCenterExportMetadataService}
*/
public class SingleRegistryCenterExportMetadataServiceImpl implements SingleRegistryCenterExportMetadataService {
/**
* {@inheritDoc}
*/
@Override
public String hello(String name) {
return "Hello " + name;
}
}
| 8,521 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportmetadata;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener;
import org.apache.dubbo.metadata.MetadataService;
/**
* This implementation of {@link ServiceListener} is to record exported metadata services in single registry center.
*/
public class SingleRegistryCenterExportMetadataServiceListener extends AbstractRegistryCenterServiceListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return MetadataService.class;
}
}
| 8,522 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataIntegrationTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportmetadata;
import org.apache.dubbo.common.extension.ExtensionLoader;
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.ServiceListener;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.integration.IntegrationTest;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
/**
* The testcases are only for checking the process of exporting metadata service.
*/
class SingleRegistryCenterExportMetadataIntegrationTest implements IntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(SingleRegistryCenterExportMetadataIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "single-registry-center-export-metadata";
/**
* The name for getting the specified instance, which is loaded using SPI.
*/
private static String SPI_NAME = "singleConfigCenterExportMetadata";
/**
* Define the protocol's name.
*/
private static String PROTOCOL_NAME = "injvm";
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<SingleRegistryCenterExportMetadataService> serviceConfig;
/**
* The listener to record exported services
*/
private SingleRegistryCenterExportMetadataServiceListener serviceListener;
/**
* The listener to record exported exporters.
*/
private SingleRegistryCenterExportMetadataExporterListener exporterListener;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize service config
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(SingleRegistryCenterExportMetadataService.class);
serviceConfig.setRef(new SingleRegistryCenterExportMetadataServiceImpl());
serviceConfig.setAsync(false);
serviceConfig.setScope(SCOPE_LOCAL);
// initailize bootstrap
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig(PROTOCOL_NAME))
.service(serviceConfig);
RegistryConfig registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress());
DubboBootstrap.getInstance().registry(registryConfig);
}
/**
* Define {@link ServiceListener}, {@link ExporterListener} and {@link Filter} for helping check.
* <p>Use SPI to load them before exporting.
* <p>After that, there are some checkpoints need to verify as follow:
* <ul>
* <li>There is nothing in ServiceListener or not</li>
* <li>There is nothing in ExporterListener or not</li>
* <li>ServiceConfig is exported or not</li>
* </ul>
*/
private void beforeExport() {
// ---------------initialize--------------- //
serviceListener = (SingleRegistryCenterExportMetadataServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME);
exporterListener = (SingleRegistryCenterExportMetadataExporterListener)
ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME);
// ---------------checkpoints--------------- //
// There is nothing in ServiceListener
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
// There is nothing in ExporterListener
Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty());
// ServiceConfig isn't exported
Assertions.assertFalse(serviceConfig.isExported());
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void integrate() {
beforeExport();
DubboBootstrap.getInstance().start();
afterExport();
}
/**
* There are some checkpoints need to check after exported as follow:
* <ul>
* <li>The metadata service is only one or not</li>
* <li>The exported service is MetadataService or not</li>
* <li>The MetadataService is exported or not</li>
* <li>The exported exporters are right or not</li>
* </ul>
*/
private void afterExport() {
// The metadata service is only one
Assertions.assertEquals(serviceListener.getExportedServices().size(), 1);
// The exported service is MetadataService
Assertions.assertEquals(
serviceListener.getExportedServices().get(0).getInterfaceClass(), MetadataService.class);
// The MetadataService is exported
Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported());
// There are two exported exporters
// 1. Metadata Service exporter with Injvm protocol
// 2. SingleRegistryCenterExportMetadataService exporter with Injvm protocol
Assertions.assertEquals(exporterListener.getExportedExporters().size(), 2);
List<Exporter<?>> injvmExporters = exporterListener.getExportedExporters().stream()
.filter(exporter -> PROTOCOL_NAME.equalsIgnoreCase(
exporter.getInvoker().getUrl().getProtocol()))
.collect(Collectors.toList());
// Make sure there are 2 injvmExporters
Assertions.assertEquals(injvmExporters.size(), 2);
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
PROVIDER_APPLICATION_NAME = null;
serviceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
serviceListener = null;
logger.info(getClass().getSimpleName() + " testcase is ending...");
}
}
| 8,523 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportmetadata;
/**
* This interface is used to check if the exported metadata service works well or not.
*/
public interface SingleRegistryCenterExportMetadataService {
/**
* The simple method for testing.
*/
String hello(String name);
}
| 8,524 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/exportmetadata/SingleRegistryCenterExportMetadataExporterListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.integration.single.exportmetadata;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener;
import org.apache.dubbo.metadata.MetadataService;
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class SingleRegistryCenterExportMetadataExporterListener extends AbstractRegistryCenterExporterListener {
/**
* Returns the interface of exported service.
*/
@Override
protected Class<?> getInterface() {
return MetadataService.class;
}
}
| 8,525 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.Transporter;
import org.mockito.Mockito;
public class MockTransporter implements Transporter {
private RemotingServer server = Mockito.mock(RemotingServer.class);
private Client client = Mockito.mock(Client.class);
@Override
public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException {
return server;
}
@Override
public Client connect(URL url, ChannelHandler handler) throws RemotingException {
return client;
}
}
| 8,526 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExchanger.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.ExchangeHandler;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchanger;
public class MockExchanger implements Exchanger {
@Override
public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException {
return null;
}
@Override
public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException {
return null;
}
}
| 8,527 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock1.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
public class GreetingMock1 {}
| 8,528 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcException;
public class MockProtocol2 implements Protocol {
public static Protocol delegate;
@Override
public int getDefaultPort() {
return delegate.getDefaultPort();
}
@Override
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
return delegate.export(invoker);
}
@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
return delegate.refer(type, url);
}
@Override
public void destroy() {
delegate.destroy();
}
}
| 8,529 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTelnetHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
public class MockTelnetHandler implements TelnetHandler {
@Override
public String telnet(Channel channel, String message) throws RemotingException {
return null;
}
}
| 8,530 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistry.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import java.util.ArrayList;
import java.util.List;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
/**
* TODO Comment of MockRegistry
*/
public class MockRegistry implements Registry {
static URL subscribedUrl = new ServiceConfigURL("null", "0.0.0.0", 0);
public static URL getSubscribedUrl() {
return subscribedUrl;
}
/*
* @see org.apache.dubbo.common.Node#getUrl()
*/
public URL getUrl() {
return null;
}
/*
* @see org.apache.dubbo.common.Node#isAvailable()
*/
@Override
public boolean isAvailable() {
return true;
}
/*
* @see org.apache.dubbo.common.Node#destroy()
*/
@Override
public void destroy() {}
/*
* @see org.apache.dubbo.registry.RegistryService#register(org.apache.dubbo.common.URL)
*/
@Override
public void register(URL url) {}
/*
* @see org.apache.dubbo.registry.RegistryService#unregister(org.apache.dubbo.common.URL)
*/
@Override
public void unregister(URL url) {}
/*
* @see org.apache.dubbo.registry.RegistryService#subscribe(org.apache.dubbo.common.URL, org.apache.dubbo.registry.NotifyListener)
*/
@Override
public void subscribe(URL url, NotifyListener listener) {
this.subscribedUrl = url;
List<URL> urls = new ArrayList<URL>();
urls.add(url.setProtocol("mockprotocol").removeParameter(CATEGORY_KEY).addParameter(METHODS_KEY, "sayHello"));
listener.notify(urls);
}
/*
* @see org.apache.dubbo.registry.RegistryService#unsubscribe(org.apache.dubbo.common.URL, org.apache.dubbo.registry.NotifyListener)
*/
@Override
public void unsubscribe(URL url, NotifyListener listener) {}
/*
* @see org.apache.dubbo.registry.RegistryService#lookup(org.apache.dubbo.common.URL)
*/
@Override
public List<URL> lookup(URL url) {
return null;
}
}
| 8,531 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockLoadBalance.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import java.util.List;
public class MockLoadBalance implements LoadBalance {
@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
return null;
}
}
| 8,532 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockThreadPool.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.ThreadPool;
import java.util.concurrent.Executor;
public class MockThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
return null;
}
}
| 8,533 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockInvokerListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.RpcException;
public class MockInvokerListener implements InvokerListener {
@Override
public void referred(Invoker<?> invoker) throws RpcException {}
@Override
public void destroyed(Invoker<?> invoker) {}
}
| 8,534 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.config.api.Greeting;
public class GreetingLocal2 implements Greeting {
@Override
public String hello() {
return "local";
}
}
| 8,535 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.metadata.MetadataService;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MockServiceListener implements ServiceListener {
private Map<String, ServiceConfig> exportedServices = new ConcurrentHashMap<>();
@Override
public void exported(ServiceConfig sc) {
// Ignore MetadataService
if (sc.getInterfaceClass() == MetadataService.class) {
return;
}
exportedServices.put(sc.getUniqueServiceName(), sc);
}
@Override
public void unexported(ServiceConfig sc) {}
public Map<String, ServiceConfig> getExportedServices() {
return exportedServices;
}
public void clearExportedServices() {
exportedServices.clear();
}
}
| 8,536 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCluster.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.Directory;
public class MockCluster implements Cluster {
@Override
public <T> Invoker<T> join(Directory<T> directory, boolean buildFilterChain) throws RpcException {
return null;
}
}
| 8,537 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal3.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.config.api.Greeting;
public class GreetingLocal3 implements Greeting {
private Greeting greeting;
public GreetingLocal3(Greeting greeting) {
this.greeting = greeting;
}
@Override
public String hello() {
return null;
}
}
| 8,538 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockCodec.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Codec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MockCodec implements Codec {
@Override
public void encode(Channel channel, OutputStream output, Object message) throws IOException {}
@Override
public Object decode(Channel channel, InputStream input) throws IOException {
return null;
}
}
| 8,539 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProtocol.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.mockito.Mockito;
public class MockProtocol implements Protocol {
/* (non-Javadoc)
* @see org.apache.dubbo.rpc.Protocol#getDefaultPort()
*/
@Override
public int getDefaultPort() {
return 0;
}
/* (non-Javadoc)
* @see org.apache.dubbo.rpc.Protocol#export(org.apache.dubbo.rpc.Invoker)
*/
@Override
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
return Mockito.mock(Exporter.class);
}
/* (non-Javadoc)
* @see org.apache.dubbo.rpc.Protocol#refer(java.lang.Class, org.apache.dubbo.common.URL)
*/
@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
final URL u = url;
return new Invoker<T>() {
@Override
public Class<T> getInterface() {
return null;
}
public URL getUrl() {
return u;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return null;
}
@Override
public void destroy() {}
};
}
/* (non-Javadoc)
* @see org.apache.dubbo.rpc.Protocol#destroy()
*/
@Override
public void destroy() {}
}
| 8,540 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockProxyFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcException;
public class MockProxyFactory implements ProxyFactory {
@Override
public <T> T getProxy(Invoker<T> invoker) throws RpcException {
return null;
}
@Override
public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException {
return null;
}
@Override
public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException {
return null;
}
}
| 8,541 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
/**
* TODO Comment of MockRegistryFactory
*/
public class MockRegistryFactory implements RegistryFactory {
/*
* @see org.apache.dubbo.registry.RegistryFactory#getRegistry(org.apache.dubbo.common.URL)
*/
@Override
public Registry getRegistry(URL url) {
return new MockRegistry();
}
}
| 8,542 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockServiceDiscovery.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MockServiceDiscovery extends AbstractServiceDiscovery {
private URL registryURL;
public MockServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
}
public MockServiceDiscovery(String serviceName, URL registryURL) {
super(serviceName, registryURL);
}
@Override
public void doDestroy() throws Exception {}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {
this.serviceInstance = serviceInstance;
}
@Override
protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance)
throws RuntimeException {
this.serviceInstance = newServiceInstance;
}
@Override
public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {
this.serviceInstance = null;
}
@Override
public Set<String> getServices() {
return new HashSet<>();
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return Collections.emptyList();
}
@Override
public URL getUrl() {
return registryURL;
}
}
| 8,543 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingLocal1.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
public class GreetingLocal1 {}
| 8,544 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockDispatcher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
public class MockDispatcher implements Dispatcher {
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return null;
}
}
| 8,545 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockExporterListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.RpcException;
public class MockExporterListener implements ExporterListener {
@Override
public void exported(Exporter<?> exporter) throws RpcException {}
@Override
public void unexported(Exporter<?> exporter) {}
}
| 8,546 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/TestProxyFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.proxy.jdk.JdkProxyFactory;
public class TestProxyFactory extends JdkProxyFactory {
public static int count = 0;
@Override
public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException {
count++;
return super.getInvoker(proxy, type, url);
}
}
| 8,547 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/GreetingMock2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.config.api.Greeting;
public class GreetingMock2 implements Greeting {
private GreetingMock2() {}
@Override
public String hello() {
return "mock";
}
}
| 8,548 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
public class MockFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return null;
}
}
| 8,549 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockStatusChecker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
public class MockStatusChecker implements StatusChecker {
@Override
public Status check() {
return null;
}
}
| 8,550 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockRegistryFactory2.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
public class MockRegistryFactory2 implements RegistryFactory {
public static Registry registry;
@Override
public Registry getRegistry(URL url) {
return registry;
}
}
| 8,551 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/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.provider.impl;
import org.apache.dubbo.config.api.Box;
import org.apache.dubbo.config.api.DemoException;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.api.User;
import java.util.List;
/**
* DemoServiceImpl
*/
public class DemoServiceImpl implements DemoService {
public String sayName(String name) {
return "say:" + name;
}
public Box getBox() {
return null;
}
public void throwDemoException() throws DemoException {
throw new DemoException("DemoServiceImpl");
}
public List<User> getUsers(List<User> users) {
return users;
}
public int echo(int i) {
return i;
}
}
| 8,552 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/XxxMockReferenceConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ReferenceConfig;
import org.apache.dubbo.config.utils.service.XxxService;
import java.util.concurrent.atomic.AtomicLong;
public class XxxMockReferenceConfig extends ReferenceConfig<XxxService> {
static AtomicLong counter = new AtomicLong();
XxxService value;
boolean destroyMethodRun = false;
public static void setCounter(long c) {
counter.set(c);
}
public boolean isGetMethodRun() {
return value != null;
}
public boolean isDestroyMethodRun() {
return destroyMethodRun;
}
@Override
public synchronized XxxService get(boolean check) {
if (value != null) return value;
counter.getAndIncrement();
value = super.get(check);
return value;
}
public long getCounter() {
return counter.get();
}
@Override
public synchronized void destroy() {
super.destroy();
destroyMethodRun = true;
}
}
| 8,553 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ConfigValidationUtilsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.config.AbstractInterfaceConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.config.mock.GreetingMock1;
import org.apache.dubbo.config.mock.GreetingMock2;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_CLASS_NOT_FOUND;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class ConfigValidationUtilsTest {
@Test
void checkMock1() {
Assertions.assertThrows(IllegalStateException.class, () -> {
InterfaceConfig interfaceConfig = new InterfaceConfig();
interfaceConfig.setMock("return {a, b}");
ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig);
});
}
@Test
void checkMock2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
InterfaceConfig interfaceConfig = new InterfaceConfig();
interfaceConfig.setMock(GreetingMock1.class.getName());
ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig);
});
}
@Test
void checkMock3() {
Assertions.assertThrows(IllegalStateException.class, () -> {
InterfaceConfig interfaceConfig = new InterfaceConfig();
interfaceConfig.setMock(GreetingMock2.class.getName());
ConfigValidationUtils.checkMock(Greeting.class, interfaceConfig);
});
}
@Test
void testValidateMetadataConfig() {
MetadataReportConfig config = new MetadataReportConfig();
config.setAddress("protocol://ip:host");
try {
ConfigValidationUtils.validateMetadataConfig(config);
} catch (Exception e) {
Assertions.fail("valid config expected.");
}
config.setAddress("ip:host");
config.setProtocol("protocol");
try {
ConfigValidationUtils.validateMetadataConfig(config);
} catch (Exception e) {
Assertions.fail("valid config expected.");
}
config.setAddress("ip:host");
config.setProtocol(null);
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ConfigValidationUtils.validateMetadataConfig(config);
});
}
@Test
void testValidateApplicationConfig() throws Exception {
try (MockedStatic<ConfigValidationUtils> mockedStatic = Mockito.mockStatic(ConfigValidationUtils.class); ) {
mockedStatic
.when(() -> ConfigValidationUtils.validateApplicationConfig(any()))
.thenCallRealMethod();
ApplicationConfig config = new ApplicationConfig();
Assertions.assertThrows(IllegalStateException.class, () -> {
ConfigValidationUtils.validateApplicationConfig(config);
});
config.setName("testName");
config.setOwner("testOwner");
config.setOrganization("testOrg");
config.setArchitecture("testArchitecture");
config.setEnvironment("test");
Map<String, String> map = new HashMap();
map.put("k1", "v1");
map.put("k2", "v2");
config.setParameters(map);
ConfigValidationUtils.validateApplicationConfig(config);
mockedStatic.verify(
() -> {
ConfigValidationUtils.checkName(any(), any());
},
times(4));
mockedStatic.verify(
() -> {
ConfigValidationUtils.checkMultiName(any(), any());
},
times(1));
mockedStatic.verify(
() -> {
ConfigValidationUtils.checkParameterName(any());
},
times(1));
}
}
@Test
void testCheckQosInApplicationConfig() throws Exception {
ConfigValidationUtils mock = Mockito.mock(ConfigValidationUtils.class);
ErrorTypeAwareLogger loggerMock = Mockito.mock(ErrorTypeAwareLogger.class);
injectField(mock.getClass().getDeclaredField("logger"), loggerMock);
ApplicationConfig config = new ApplicationConfig();
config.setName("testName");
config.setQosEnable(false);
mock.validateApplicationConfig(config);
verify(loggerMock, never()).warn(any(), any());
config.setQosEnable(true);
mock.validateApplicationConfig(config);
verify(loggerMock)
.warn(
eq(COMMON_CLASS_NOT_FOUND),
eq(""),
eq(""),
eq(
"No QosProtocolWrapper class was found. Please check the dependency of dubbo-qos whether was imported correctly."),
any());
}
private void injectField(Field field, Object newValue) throws Exception {
field.setAccessible(true);
field.set(null, newValue);
}
public static class InterfaceConfig extends AbstractInterfaceConfig {}
}
| 8,554 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/MockReferenceConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ReferenceConfig;
import org.apache.dubbo.config.utils.service.FooService;
import java.util.concurrent.atomic.AtomicLong;
public class MockReferenceConfig extends ReferenceConfig<FooService> {
static AtomicLong counter = new AtomicLong();
FooService value;
boolean destroyMethodRun = false;
public static void setCounter(long c) {
counter.set(c);
}
public boolean isGetMethodRun() {
return value != null;
}
public boolean isDestroyMethodRun() {
return destroyMethodRun;
}
@Override
public synchronized FooService get(boolean check) {
if (value != null) return value;
counter.getAndIncrement();
value = super.get(check);
return value;
}
public long getCounter() {
return counter.get();
}
@Override
public synchronized void destroy() {
super.destroy();
destroyMethodRun = true;
}
}
| 8,555 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/ReferenceCacheTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.config.ReferenceCache;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.utils.service.FooService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ReferenceCacheTest {
@BeforeEach
public void setUp() throws Exception {
DubboBootstrap.reset();
MockReferenceConfig.setCounter(0);
SimpleReferenceCache.CACHE_HOLDER.clear();
}
@Test
void testGetCacheSameReference() throws Exception {
ReferenceCache cache = SimpleReferenceCache.getCache();
MockReferenceConfig config =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
assertEquals(0L, config.getCounter());
Object proxy = cache.get(config);
assertTrue(config.isGetMethodRun());
// singleton reference config by default
MockReferenceConfig configCopy =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
assertEquals(1L, configCopy.getCounter());
Object proxyOfCopyConfig = cache.get(configCopy);
assertFalse(configCopy.isGetMethodRun());
assertEquals(1L, config.getCounter());
assertEquals(1L, configCopy.getCounter());
assertEquals(proxy, proxyOfCopyConfig);
}
@Test
void testGetCacheDiffReference() throws Exception {
ReferenceCache cache = SimpleReferenceCache.getCache();
MockReferenceConfig config =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
assertEquals(0L, config.getCounter());
cache.get(config);
assertEquals(1L, config.getCounter());
assertTrue(config.isGetMethodRun());
cache.get(config);
assertEquals(1L, config.getCounter());
XxxMockReferenceConfig configCopy =
buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0");
assertEquals(0L, configCopy.getCounter());
cache.get(configCopy);
assertTrue(configCopy.isGetMethodRun());
assertEquals(1L, configCopy.getCounter());
}
@Test
void testGetCacheWithKey() throws Exception {
ReferenceCache cache = SimpleReferenceCache.getCache();
MockReferenceConfig config =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
FooService value = cache.get(config);
assertEquals(
value, cache.get("group1/org.apache.dubbo.config.utils.service.FooService:1.0.0", FooService.class));
}
@Test
void testGetCacheDiffName() throws Exception {
SimpleReferenceCache cache = SimpleReferenceCache.getCache();
MockReferenceConfig config =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
assertEquals(0L, config.getCounter());
cache.get(config);
assertTrue(config.isGetMethodRun());
assertEquals(1L, config.getCounter());
cache = SimpleReferenceCache.getCache("foo");
config = buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
assertEquals(1L, config.getCounter());
cache.get(config);
// still init for the same ReferenceConfig if the cache is different
assertTrue(config.isGetMethodRun());
assertEquals(2L, config.getCounter());
}
@Test
void testDestroy() throws Exception {
SimpleReferenceCache cache = SimpleReferenceCache.getCache();
MockReferenceConfig config =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
cache.get(config);
XxxMockReferenceConfig configCopy =
buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0");
cache.get(configCopy);
assertEquals(2, cache.getReferenceMap().size());
cache.destroy(config);
assertTrue(config.isDestroyMethodRun());
assertEquals(1, cache.getReferenceMap().size());
cache.destroy(configCopy);
assertTrue(configCopy.isDestroyMethodRun());
assertEquals(0, cache.getReferenceMap().size());
}
@Test
void testDestroyAll() throws Exception {
SimpleReferenceCache cache = SimpleReferenceCache.getCache();
MockReferenceConfig config =
buildMockReferenceConfig("org.apache.dubbo.config.utils.service.FooService", "group1", "1.0.0");
cache.get(config);
XxxMockReferenceConfig configCopy =
buildXxxMockReferenceConfig("org.apache.dubbo.config.utils.service.XxxService", "group1", "1.0.0");
cache.get(configCopy);
assertEquals(2, cache.getReferenceMap().size());
cache.destroyAll();
assertTrue(config.isDestroyMethodRun());
assertTrue(configCopy.isDestroyMethodRun());
assertEquals(0, cache.getReferenceMap().size());
}
private MockReferenceConfig buildMockReferenceConfig(String service, String group, String version) {
MockReferenceConfig config = new MockReferenceConfig();
config.setApplication(new ApplicationConfig("cache"));
config.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234"));
config.setCheck(false);
config.setInterface(service);
config.setGroup(group);
config.setVersion(version);
return config;
}
private XxxMockReferenceConfig buildXxxMockReferenceConfig(String service, String group, String version) {
XxxMockReferenceConfig config = new XxxMockReferenceConfig();
config.setApplication(new ApplicationConfig("cache"));
config.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234"));
config.setInterface(service);
config.setCheck(false);
config.setGroup(group);
config.setVersion(version);
return config;
}
}
| 8,556 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.service;
/**
*
*/
public interface FooService {}
| 8,557 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.service;
/**
*
*/
public class XxxServiceImpl implements XxxService {}
| 8,558 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.service;
/**
*
*/
public class FooServiceImpl implements FooService {}
| 8,559 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.service;
/**
*
*/
public interface XxxService {}
| 8,560 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.config.ServiceConfig;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.sameInstance;
class DelegateProviderMetaDataInvokerTest {
private ServiceConfig service;
private Invoker<Greeting> invoker;
@BeforeEach
public void setUp() throws Exception {
service = Mockito.mock(ServiceConfig.class);
invoker = Mockito.mock(Invoker.class);
}
@Test
void testDelegate() {
DelegateProviderMetaDataInvoker<Greeting> delegate =
new DelegateProviderMetaDataInvoker<Greeting>(invoker, service);
delegate.getInterface();
Mockito.verify(invoker).getInterface();
delegate.getUrl();
Mockito.verify(invoker).getUrl();
delegate.isAvailable();
Mockito.verify(invoker).isAvailable();
Invocation invocation = Mockito.mock(Invocation.class);
delegate.invoke(invocation);
Mockito.verify(invoker).invoke(invocation);
delegate.destroy();
Mockito.verify(invoker).destroy();
assertThat(delegate.getMetadata(), sameInstance(service));
}
}
| 8,561 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/ExporterSideConfigUrlTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.url;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ExporterSideConfigUrlTest extends UrlTestBase {
private static final Logger log = LoggerFactory.getLogger(ExporterSideConfigUrlTest.class);
// ======================================================
// tests start
// ======================================================
@BeforeAll
public static void start() {}
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
initServConf();
}
@AfterEach()
public void teardown() {
DubboBootstrap.reset();
}
@Test
void exporterMethodConfigUrlTest() {
verifyExporterUrlGeneration(methodConfForService, methodConfForServiceTable);
}
@Test
void exporterServiceConfigUrlTest() {
verifyExporterUrlGeneration(servConf, servConfTable);
}
@Test
void exporterProviderConfigUrlTest() {
verifyExporterUrlGeneration(provConf, provConfTable);
}
@Test
void exporterRegistryConfigUrlTest() {
// verifyExporterUrlGeneration(regConfForService, regConfForServiceTable);
}
protected <T> void verifyExporterUrlGeneration(T config, Object[][] dataTable) {
// 1. fill corresponding config with data
////////////////////////////////////////////////////////////
fillConfigs(config, dataTable, TESTVALUE1);
// 2. export service and get url parameter string from db
////////////////////////////////////////////////////////////
servConf.export();
String paramStringFromDb = getProviderParamString();
try {
paramStringFromDb = URLDecoder.decode(paramStringFromDb, "UTF-8");
} catch (UnsupportedEncodingException e) {
// impossible
}
assertUrlStringWithLocalTable(
paramStringFromDb, dataTable, config.getClass().getName(), TESTVALUE1);
// 4. unexport service
////////////////////////////////////////////////////////////
servConf.unexport();
}
}
| 8,562 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/UrlTestBase.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.url;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.provider.impl.DemoServiceImpl;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.fail;
@SuppressWarnings("unused")
public class UrlTestBase {
// ======================================================
// data column definition
// ======================================================
protected static final int KEY = 0;
protected static final int URL_KEY = 1;
protected static final int TESTVALUE1 = 4;
private static final Logger log = LoggerFactory.getLogger(UrlTestBase.class);
private static final int TYPE = 2;
private static final int DEFAULT = 3;
private static final int TESTVALUE2 = 5;
private static final int TESTVALUE3 = 6;
private static final int TESTVALUE4 = 7;
private static final int TESTVALUE5 = 8;
private static final int TESTVALUE6 = 9;
private static final int TESTVALUE7 = 10;
protected ApplicationConfig application;
protected RegistryConfig regConfForProvider;
protected RegistryConfig regConfForService;
protected ProviderConfig provConf;
protected ProtocolConfig protoConfForProvider;
protected ProtocolConfig protoConfForService;
protected MethodConfig methodConfForService;
protected ServiceConfig<DemoService> servConf;
protected Object servConfTable[][] = {
{"proxy", "proxy", "string", "javassist", "jdk", "javassist", "", "", "", ""},
{"actives", "actives", "int", 0, 90, "", "", "", "", ""},
{"executes", "executes", "int", 0, 90, "", "", "", "", ""},
{"deprecated", "deprecated", "boolean", false, true, "", "", "", "", ""},
{"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""},
{"accesslog", "accesslog", "string", "", "haominTest", "", "", "", "", ""},
{
"document",
"document",
"string",
"",
"http://dubbo.apache.org/zh-cn/docs/user/quick-start.html?testquery=你好你好",
"",
"",
"",
"",
""
},
{"weight", "weight", "int", 0, 90, "", "", "", "", ""},
// {"filter", "service.filter", "string", "", "", "", "", "", "", ""},
// {"listener", "listener", "string", "", "", "", "", "", "", ""},
};
protected Object regConfForServiceTable[][] = {
// {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""},
// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""},
// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""},
// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""},
// {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""},
{"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""},
};
protected Object provConfTable[][] = {
{"cluster", "cluster", "string", "string", "failover", "failfast", "failsafe", "", "", ""},
{"async", "async", "boolean", false, true, "", "", "", "", ""},
{"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""},
{"connections", "connections", "int", 0, 60, "", "", "", "", ""},
{"retries", "retries", "int", 2, 60, "", "", "", "", ""},
{"timeout", "timeout", "int", 5000, 60, "", "", "", "", ""},
// change by fengting listener 没有缺省值
// {"listener", "exporter.listener", "string", "", "", "", "", "", "", ""},
// {"filter", "service.filter", "string", "", "", "", "", "", "", ""},
};
protected Object methodConfForServiceTable[][] = {
{"actives", "sayName.actives", "int", 0, 90, "", "", "", "", ""},
{"executes", "sayName.executes", "int", 0, 90, "", "", "", "", ""},
{"deprecated", "sayName.deprecated", "boolean", false, true, "", "", "", "", ""},
{"async", "sayName.async", "boolean", false, true, "", "", "", "", ""},
{"timeout", "sayName.timeout", "int", 0, 90, "", "", "", "", ""},
};
protected DemoService demoService = new DemoServiceImpl();
private Object appConfForProviderTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
private Object appConfForServiceTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
private Object regConfForProviderTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
private Object protoConfForProviderTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
private Object protoConfForServiceTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
// ======================================================
// data table manipulation utils
// ======================================================
protected String genParamString(Object urlKey, Object value) {
return (String) urlKey + "=" + value.toString();
}
protected <T> void fillConfigs(T conf, Object[][] table, int column) {
for (Object[] row : table) {
fillConfig(conf, row, column);
}
}
protected <T> void fillConfig(T conf, Object[] row, int column) {
RpcConfigGetSetProxy proxy = new RpcConfigGetSetProxy(conf);
proxy.setValue((String) row[KEY], row[column]);
}
@SuppressWarnings("deprecation")
protected void initServConf() {
regConfForProvider = new RegistryConfig();
regConfForService = new RegistryConfig();
provConf = new ProviderConfig();
protoConfForProvider = new ProtocolConfig("mockprotocol");
protoConfForService = new ProtocolConfig("mockprotocol");
methodConfForService = new MethodConfig();
servConf = new ServiceConfig<DemoService>();
// provConf.setApplication(appConfForProvider);
application = new ApplicationConfig();
application.setMetadataServicePort(20881);
servConf.setApplication(application);
provConf.setRegistry(regConfForProvider);
servConf.setRegistry(regConfForService);
provConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForProvider)));
servConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForService)));
servConf.setMethods(Arrays.asList(new MethodConfig[] {methodConfForService}));
servConf.setProvider(provConf);
servConf.setRef(demoService);
servConf.setInterfaceClass(DemoService.class);
methodConfForService.setName("sayName");
regConfForService.setAddress("127.0.0.1:9090");
regConfForService.setProtocol("mockregistry");
application.setName("ConfigTests");
}
protected String getProviderParamString() {
return servConf.getExportedUrls().get(0).toString();
}
/**
* @param paramStringFromDb
* @param dataTable
* @param configName
* @param column
*/
protected void assertUrlStringWithLocalTable(
String paramStringFromDb, Object[][] dataTable, String configName, int column) {
final String FAILLOG_HEADER = "The following config items are not found in URLONE: ";
log.warn("Verifying service url for " + configName + "... ");
log.warn("Consumer url string: " + paramStringFromDb);
String failLog = FAILLOG_HEADER;
for (Object[] row : dataTable) {
String targetString = genParamString(row[URL_KEY], row[column]);
log.warn("Checking " + (String) row[KEY] + "for" + targetString);
if (paramStringFromDb.contains(targetString)) {
log.warn((String) row[KEY] + " --> " + targetString + " OK!");
} else {
failLog += targetString + ", ";
}
}
if (!failLog.equals(FAILLOG_HEADER)) {
fail(failLog);
}
}
}
| 8,563 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/InvokerSideConfigUrlTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.url;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.mock.MockRegistry;
import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
@Disabled
class InvokerSideConfigUrlTest extends UrlTestBase {
private static final Logger log = LoggerFactory.getLogger(InvokerSideConfigUrlTest.class);
// ======================================================
// invoker related data preparing
// ======================================================
private RegistryConfig regConfForConsumer;
private RegistryConfig regConfForReference;
private MethodConfig methodConfForReference;
private ConsumerConfig consumerConf;
private ReferenceConfig<DemoService> refConf;
private Object appConfForConsumerTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
private Object appConfForReferenceTable[][] = {
{"", "", "", "", "", "", "", "", "", ""},
};
private Object regConfForConsumerTable[][] = {
// {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""},
// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""},
// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""},
// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""},
{"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""},
{"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""},
};
private Object regConfForReferenceTable[][] = {
{"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""},
{"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""},
{"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""},
{"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""},
{"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""},
{"dynamic", "dynamic", "boolean", true, false, "", "", "", "", ""},
};
private Object methodConfForReferenceTable[][] = {
{"actives", "eatTiger.actives", "int", 0, 90, "", "", "", "", ""},
{"executes", "eatTiger.executes", "int", 0, 90, "", "", "", "", ""},
{"deprecated", "eatTiger.deprecated", "boolean", false, true, "", "", "", "", ""},
{"async", "eatTiger.async", "boolean", false, true, "", "", "", "", ""},
{"timeout", "eatTiger.timeout", "int", 0, 90, "", "", "", "", ""},
};
private Object refConfTable[][] = {
// {"version", "version", "string", "0.0.0", "1.2.3", "", "", "", "", ""},
// {"group", "group", "string", "", "HaominTest", "", "", "", "", ""},
// {"delay", "delay", "int", 0, 5, "", "", "", "", ""}, // not boolean
{"timeout", "timeout", "int", 5000, 3000, "", "", "", "", ""},
{"retries", "retries", "int", 2, 5, "", "", "", "", ""},
{"connections", "connections", "boolean", 100, 20, "", "", "", "", ""},
{"loadbalance", "loadbalance", "string", "random", "roundrobin", "leastactive", "", "", ""},
{"async", "async", "boolean", false, true, "", "", "", "", ""},
// excluded = true
// {"generic", "generic", "boolean", false, true, "", "", "", "", ""},
{"check", "check", "boolean", false, true, "", "", "", "", ""},
// {"local", "local", "string", "false", "HelloServiceLocal", "true", "", "", "", ""},
// {"local", "local", "string", "false", "true", "", "", "", "", ""},
// {"mock", "mock", "string", "false", "dubbo.test.HelloServiceMock", "true", "", "", "", ""},
{"mock", "mock", "string", "false", "false", "", "", "", "", ""},
{"proxy", "proxy", "boolean", "javassist", "jdk", "", "", "", "", ""},
{"client", "client", "string", "netty", "mina", "", "", "", "", ""},
{"client", "client", "string", "netty", "mina", "", "", "", "", ""},
{"owner", "owner", "string", "", "haomin,ludvik", "", "", "", "", ""},
{"actives", "actives", "int", 0, 30, "", "", "", "", ""},
{"cluster", "cluster", "string", "failover", "failfast", "failsafe", "failback", "forking", "", ""},
// excluded = true
// {"filter", "service.filter", "string", "default", "-generic", "", "", "", "", ""},
// excluded = true
// {"listener", "exporter.listener", "string", "default", "-deprecated", "", "", "", "", ""},
// {"", "", "", "", "", "", "", "", "", ""},
};
private Object consumerConfTable[][] = {
{"timeout", "timeout", "int", 5000, 8000, "", "", "", "", ""},
{"retries", "retries", "int", 2, 5, "", "", "", "", ""},
{"loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", ""},
{"async", "async", "boolean", false, true, "", "", "", "", ""},
{"connections", "connections", "int", 100, 5, "", "", "", "", ""},
// {"generic", "generic", "boolean", false, false, "", "", "", "", ""},
{"check", "check", "boolean", true, false, "", "", "", "", ""},
{"proxy", "proxy", "string", "javassist", "jdk", "javassist", "", "", "", ""},
{"owner", "owner", "string", "", "haomin", "", "", "", "", ""},
{"actives", "actives", "int", 0, 5, "", "", "", "", ""},
{"cluster", "cluster", "string", "failover", "forking", "", "", "", "", ""},
{"filter", "", "string", "", "", "", "", "", "", ""},
{"listener", "", "string", "", "", "", "", "", "", ""},
// {"", "", "", "", "", "", "", "", "", ""},
};
// ======================================================
// test Start
// ======================================================
@BeforeAll
public static void start() {
// RegistryController.startRegistryIfAbsence(1);
}
@BeforeEach
public void setUp() {
initServConf();
initRefConf();
// ApplicationModel.defaultModel().getConfigManager().clear();
}
@AfterEach()
public void teardown() {
// RegistryServer.reloadCache();
// ApplicationModel.defaultModel().getConfigManager().clear();
}
@Test
void consumerConfUrlTest() {
verifyInvokerUrlGeneration(consumerConf, consumerConfTable);
}
@Test
void refConfUrlTest() {
verifyInvokerUrlGeneration(refConf, refConfTable);
}
@Disabled(
"parameter on register center will not be merged any longer with query parameter request from the consumer")
@Test
void regConfForConsumerUrlTest() {
verifyInvokerUrlGeneration(regConfForConsumer, regConfForConsumerTable);
}
// ======================================================
// private helper
// ======================================================
private void initRefConf() {
regConfForConsumer = new RegistryConfig();
regConfForReference = new RegistryConfig();
methodConfForReference = new MethodConfig();
refConf = new ReferenceConfig<DemoService>();
consumerConf = new ConsumerConfig();
methodConfForReference.setName("sayName");
regConfForReference.setAddress("127.0.0.1:9090");
regConfForReference.setProtocol("mockregistry");
refConf.setInterface("org.apache.dubbo.config.api.DemoService");
refConf.setApplication(application);
// consumerConf.setApplication(appConfForConsumer);
refConf.setRegistry(regConfForReference);
consumerConf.setRegistry(regConfForConsumer);
refConf.setConsumer(consumerConf);
refConf.setMethods(Arrays.asList(new MethodConfig[] {methodConfForReference}));
refConf.setScope(SCOPE_REMOTE);
}
private <T> void verifyInvokerUrlGeneration(T config, Object[][] dataTable) {
servConf.export();
fillConfigs(config, dataTable, TESTVALUE1);
refConf.get();
String subScribedUrlStr = getSubscribedUrlString();
System.out.println("url string=========:" + subScribedUrlStr);
String configName = config.getClass().getName();
int column = TESTVALUE1;
assertUrlStringWithLocalTable(subScribedUrlStr, dataTable, configName, column);
try {
refConf.destroy();
} catch (Exception e) {
}
}
private String getSubscribedUrlString() {
return MockRegistry.getSubscribedUrl().toString();
}
}
| 8,564 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/url/RpcConfigGetSetProxy.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.url;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.AbstractConfig;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class RpcConfigGetSetProxy {
private static final String RPC_CONFIG_BASECLASS = AbstractConfig.class.getName();
private static final Logger log = LoggerFactory.getLogger(RpcConfigGetSetProxy.class);
private Object proxiee = null;
private Class<?> proxieeClass = null;
private Boolean isOk = false;
public RpcConfigGetSetProxy(Object p) {
if (p == null) {
return;
}
if (!isKindOf(p.getClass(), RPC_CONFIG_BASECLASS)) {
return;
}
proxiee = p;
// proxieeClass = c;
proxieeClass = p.getClass();
isOk = true;
}
public static boolean isKindOf(Class<?> c, String type) {
// get the class def for obj and type
Class<?> tClass;
try {
tClass = Class.forName(type);
} catch (ClassNotFoundException e) {
return false;
}
// check against type and superclasses
while (c != null) {
if (c == tClass) return true;
c = c.getSuperclass();
}
return false;
}
public boolean isOk() {
return isOk;
}
public Object setValue(String key, Object value) {
if (!isOk()) {
return null;
}
Method m = findSetMethod(key, value, proxieeClass);
return invoke(m, value);
}
public Object getValue(String key) {
if (!isOk()) {
return null;
}
Method m = findGetMethod(key, proxieeClass);
return invoke(m, null);
}
private Object invoke(Method m, Object value) {
if (m == null) {
return null;
}
try {
if (value == null) {
return m.invoke(proxiee, (Object[]) null);
} else {
return m.invoke(proxiee, value);
}
} catch (IllegalArgumentException e) {
log.error("IllegalArgumentException", e);
return null;
} catch (IllegalAccessException e) {
log.error("IllegalAccessException", e);
return null;
} catch (InvocationTargetException e) {
log.error("InvocationTargetException", e);
return null;
}
}
private Method findGetMethod(String key, Class<?> clazz) {
Method m = findMethod(key, null, "get", clazz);
if (m != null) {
return m;
}
return findMethod(key, null, "is", clazz);
}
private Method findSetMethod(String key, Object value, Class<?> clazz) {
return findMethod(key, value, "set", clazz);
}
private Method getMethod(String methodName, Object value, Class<?> clazz) {
try {
if (value == null) {
return clazz.getMethod(methodName, (Class<?>[]) null);
} else {
return clazz.getMethod(methodName, value.getClass());
}
} catch (SecurityException e) {
log.error("SecurityException: " + e.getMessage());
return null;
} catch (NoSuchMethodException e) {
log.error("NoSuchMethodException: " + e.getMessage());
return null;
}
}
private Method findMethod(String key, Object value, String prefix, Class<?> clazz) {
if (key.length() < 2) {
return null;
}
key = key.substring(0, 1).toUpperCase() + key.substring(1);
String methodName = prefix + key;
return getMethod(methodName, value, clazz);
}
}
| 8,565 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/common/Person.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.common;
import java.io.Serializable;
/**
* Person.java
*/
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
| 8,566 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.api;
/**
* DemoException
*/
public class DemoException extends Exception {
private static final long serialVersionUID = -8213943026163641747L;
public DemoException() {
super();
}
public DemoException(String message, Throwable cause) {
super(message, cause);
}
public DemoException(String message) {
super(message);
}
public DemoException(Throwable cause) {
super(cause);
}
}
| 8,567 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.api;
import java.io.Serializable;
/**
* User
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public User() {}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name == null ? -1 : name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof User)) {
return false;
}
User other = (User) obj;
if (this == other) {
return true;
}
if (name != null && other.name != null) {
return name.equals(other.name);
}
return false;
}
}
| 8,568 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.api;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface Greeting {
String hello();
}
| 8,569 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.api;
import java.io.Serializable;
import java.util.List;
/**
* DemoService
*/
public interface DemoService {
String sayName(String name);
Box getBox();
void throwDemoException() throws DemoException;
List<User> getUsers(List<User> users);
int echo(int i);
default InnerClass callInnerClass() {
return new InnerClass();
}
class InnerClass implements Serializable {}
}
| 8,570 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.api;
public interface Box {
String getName();
}
| 8,571 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/nested/AggregationConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class AggregationConfigTest {
@Test
void testEnabled() {
AggregationConfig aggregationConfig = new AggregationConfig();
aggregationConfig.setEnabled(true);
assertThat(aggregationConfig.getEnabled(), equalTo(true));
}
@Test
void testBucketNum() {
AggregationConfig aggregationConfig = new AggregationConfig();
aggregationConfig.setBucketNum(5);
assertThat(aggregationConfig.getBucketNum(), equalTo(5));
}
@Test
void testTimeWindowSeconds() {
AggregationConfig aggregationConfig = new AggregationConfig();
aggregationConfig.setTimeWindowSeconds(120);
assertThat(aggregationConfig.getTimeWindowSeconds(), equalTo(120));
}
}
| 8,572 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/nested/PrometheusConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.nested;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class PrometheusConfigTest {
@Test
void testExporter() {
PrometheusConfig prometheusConfig = new PrometheusConfig();
PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter();
exporter.setEnabled(true);
exporter.setEnableHttpServiceDiscovery(true);
exporter.setHttpServiceDiscoveryUrl("localhost:8080");
prometheusConfig.setExporter(exporter);
assertThat(prometheusConfig.getExporter().getEnabled(), equalTo(true));
assertThat(prometheusConfig.getExporter().getEnableHttpServiceDiscovery(), equalTo(true));
assertThat(prometheusConfig.getExporter().getHttpServiceDiscoveryUrl(), equalTo("localhost:8080"));
}
@Test
void testPushgateway() {
PrometheusConfig prometheusConfig = new PrometheusConfig();
PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway();
pushgateway.setEnabled(true);
pushgateway.setBaseUrl("localhost:9091");
pushgateway.setUsername("username");
pushgateway.setPassword("password");
pushgateway.setJob("job");
pushgateway.setPushInterval(30);
prometheusConfig.setPushgateway(pushgateway);
assertThat(prometheusConfig.getPushgateway().getEnabled(), equalTo(true));
assertThat(prometheusConfig.getPushgateway().getBaseUrl(), equalTo("localhost:9091"));
assertThat(prometheusConfig.getPushgateway().getUsername(), equalTo("username"));
assertThat(prometheusConfig.getPushgateway().getPassword(), equalTo("password"));
assertThat(prometheusConfig.getPushgateway().getJob(), equalTo("job"));
assertThat(prometheusConfig.getPushgateway().getPushInterval(), equalTo(30));
}
}
| 8,573 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.utils.JsonUtils;
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.api.DemoService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.provider.impl.DemoServiceImpl;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.IOException;
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.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
class MetadataServiceURLParamsMetadataCustomizerTest {
public DefaultServiceInstance instance;
private URL metadataServiceURL = URL.valueOf(
"dubbo://10.225.12.124:2002/org.apache.dubbo.metadata.MetadataService"
+ "?application=MetadataServiceURLParamsMetadataCustomizerTest&group=MetadataServiceURLParamsMetadataCustomizerTest"
+ "&interface=org.apache.dubbo.metadata.MetadataService&side=provider×tamp=1637573430740&version=1.0.0");
public static DefaultServiceInstance createInstance() {
return new DefaultServiceInstance("A", "127.0.0.1", 20880, ApplicationModel.defaultModel());
}
@BeforeEach
public void init() {
instance = createInstance();
}
@AfterEach
public void tearDown() throws IOException {
Mockito.framework().clearInlineMocks();
}
@Test
void test() {
DubboBootstrap providerBootstrap = DubboBootstrap.newInstance();
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(DemoService.class);
serviceConfig.setRef(new DemoServiceImpl());
serviceConfig.setDelay(1000);
ApplicationConfig applicationConfig = new ApplicationConfig("MetadataServiceURLParamsMetadataCustomizerTest");
applicationConfig.setMetadataType(DEFAULT_METADATA_STORAGE_TYPE);
providerBootstrap
.application(applicationConfig)
.registry(new RegistryConfig("N/A"))
.protocol(new ProtocolConfig("dubbo", 2002))
.service(serviceConfig);
// will start exporter.export()
providerBootstrap.start();
ApplicationModel applicationModel = providerBootstrap.getApplicationModel();
MetadataServiceURLParamsMetadataCustomizer customizer = new MetadataServiceURLParamsMetadataCustomizer();
customizer.customize(instance, applicationModel);
String val = instance.getMetadata().get(METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME);
Assertions.assertNotNull(val);
Map<String, String> map = JsonUtils.toJavaObject(val, Map.class);
Assertions.assertEquals(map.get(PORT_KEY), String.valueOf(metadataServiceURL.getPort()));
Assertions.assertEquals(map.get(PROTOCOL_KEY), metadataServiceURL.getProtocol());
Assertions.assertEquals(map.get(VERSION_KEY), metadataServiceURL.getVersion());
Assertions.assertFalse(map.containsKey(TIMESTAMP_KEY));
Assertions.assertFalse(map.containsKey(GROUP_KEY));
Assertions.assertFalse(map.containsKey(APPLICATION_KEY));
}
}
| 8,574 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegisterTypeEnum;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
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.config.annotation.Service;
import org.apache.dubbo.config.invoker.DelegateProviderMetaDataInvoker;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.event.MetricsInitEvent;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.ServerService;
import org.apache.dubbo.rpc.cluster.ConfiguratorFactory;
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.ServiceDescriptor;
import org.apache.dubbo.rpc.service.GenericService;
import java.beans.Transient;
import java.lang.reflect.Method;
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.Optional;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_EXECUTOR;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_NAME_MAPPING_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_METHOD_FOUND;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SERVER_DISCONNECTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNEXPORT_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_USE_RANDOM_PORT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.isInvalidPort;
import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY;
import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND;
import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY;
import static org.apache.dubbo.config.Constants.SCOPE_NONE;
import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.apache.dubbo.remoting.Constants.IS_PU_SERVER_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
import static org.apache.dubbo.rpc.Constants.SCOPE_KEY;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.apache.dubbo.rpc.support.ProtocolUtils.isGeneric;
public class ServiceConfig<T> extends ServiceConfigBase<T> {
private static final long serialVersionUID = 7868244018230856253L;
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceConfig.class);
/**
* A random port cache, the different protocols who have no port specified have different random port
*/
private static final Map<String, Integer> RANDOM_PORT_MAP = new HashMap<String, Integer>();
private Protocol protocolSPI;
/**
* A {@link ProxyFactory} implementation that will generate a exported service proxy,the JavassistProxyFactory is its
* default implementation
*/
private ProxyFactory proxyFactory;
private ProviderModel providerModel;
/**
* Whether the provider has been exported
*/
private transient volatile boolean exported;
/**
* The flag whether a service has unexported ,if the method unexported is invoked, the value is true
*/
private transient volatile boolean unexported;
private transient volatile AtomicBoolean initialized = new AtomicBoolean(false);
/**
* The exported services
*/
private final Map<RegisterTypeEnum, List<Exporter<?>>> exporters = new ConcurrentHashMap<>();
private final List<ServiceListener> serviceListeners = new ArrayList<>();
public ServiceConfig() {}
public ServiceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
public ServiceConfig(Service service) {
super(service);
}
public ServiceConfig(ModuleModel moduleModel, Service service) {
super(moduleModel, service);
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
protocolSPI = this.getExtensionLoader(Protocol.class).getAdaptiveExtension();
proxyFactory = this.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isExported() {
return exported;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isUnexported() {
return unexported;
}
@Override
public synchronized void unexport() {
if (!exported) {
return;
}
if (unexported) {
return;
}
if (!exporters.isEmpty()) {
for (List<Exporter<?>> es : exporters.values()) {
for (Exporter<?> exporter : es) {
try {
exporter.unregister();
} catch (Throwable t) {
logger.warn(
CONFIG_UNEXPORT_ERROR,
"",
"",
"Unexpected error occurred when unexport " + exporter,
t);
}
}
}
waitForIdle();
for (List<Exporter<?>> es : exporters.values()) {
for (Exporter<?> exporter : es) {
try {
exporter.unexport();
} catch (Throwable t) {
logger.warn(
CONFIG_UNEXPORT_ERROR,
"",
"",
"Unexpected error occurred when unexport " + exporter,
t);
}
}
}
exporters.clear();
}
unexported = true;
onUnexpoted();
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
repository.unregisterProvider(providerModel);
}
private void waitForIdle() {
int timeout = ConfigurationUtils.getServerShutdownTimeout(getScopeModel());
long idleTime = System.currentTimeMillis() - providerModel.getLastInvokeTime();
// 1. if service has idle for 10s(shutdown time), un-export directly
if (idleTime > timeout) {
return;
}
// 2. if service has idle for more than 6.7s(2/3 of shutdown time), wait for the rest time, then un-export
// directly
int tick = timeout / 3;
if (timeout - idleTime < tick) {
logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for "
+ (timeout - idleTime) + " ms to un-export");
try {
Thread.sleep(timeout - idleTime);
} catch (InterruptedException e) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", e.getMessage(), e);
Thread.currentThread().interrupt();
}
return;
}
// 3. Wait for 3.33s(1/3 of shutdown time), if service has idle for 3.33s(1/3 of shutdown time), un-export
// directly,
// otherwise wait for the rest time until idle for 3.33s(1/3 of shutdown time). The max wait time is
// 10s(shutdown time).
idleTime = 0;
long startTime = System.currentTimeMillis();
while (idleTime < tick) {
// service idle time.
idleTime = System.currentTimeMillis() - Math.max(providerModel.getLastInvokeTime(), startTime);
if (idleTime >= tick || System.currentTimeMillis() - startTime > timeout) {
return;
}
// idle rest time or timeout rest time
long waitTime = Math.min(tick - idleTime, timeout + startTime - System.currentTimeMillis());
logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for " + waitTime
+ " ms to un-export");
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", e.getMessage(), e);
Thread.currentThread().interrupt();
}
}
}
/**
* for early init serviceMetadata
*/
public void init() {
if (this.initialized.compareAndSet(false, true)) {
// load ServiceListeners from extension
ExtensionLoader<ServiceListener> extensionLoader = this.getExtensionLoader(ServiceListener.class);
this.serviceListeners.addAll(extensionLoader.getSupportedExtensionInstances());
}
initServiceMetadata(provider);
serviceMetadata.setServiceType(getInterfaceClass());
serviceMetadata.setTarget(getRef());
serviceMetadata.generateServiceKey();
}
@Override
public void export(RegisterTypeEnum registerType) {
if (this.exported) {
return;
}
if (getScopeModel().isLifeCycleManagedExternally()) {
// prepare model for reference
getScopeModel().getDeployer().prepare();
} else {
// ensure start module, compatible with old api usage
getScopeModel().getDeployer().start();
}
synchronized (this) {
if (this.exported) {
return;
}
if (!this.isRefreshed()) {
this.refresh();
}
if (this.shouldExport()) {
this.init();
if (shouldDelay()) {
// should register if delay export
doDelayExport();
} else if (Integer.valueOf(-1).equals(getDelay())
&& Boolean.parseBoolean(ConfigurationUtils.getProperty(
getScopeModel(), CommonConstants.DUBBO_MANUAL_REGISTER_KEY, "false"))) {
// should not register by default
doExport(RegisterTypeEnum.MANUAL_REGISTER);
} else {
doExport(registerType);
}
}
}
}
@Override
public void register(boolean byDeployer) {
if (!this.exported) {
return;
}
synchronized (this) {
if (!this.exported) {
return;
}
for (Exporter<?> exporter :
exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER, Collections.emptyList())) {
exporter.register();
}
if (byDeployer) {
for (Exporter<?> exporter :
exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER, Collections.emptyList())) {
exporter.register();
}
}
}
}
protected void doDelayExport() {
ExecutorRepository.getInstance(getScopeModel().getApplicationModel())
.getServiceExportExecutor()
.schedule(
() -> {
try {
doExport(RegisterTypeEnum.AUTO_REGISTER);
} catch (Exception e) {
logger.error(
CONFIG_FAILED_EXPORT_SERVICE,
"configuration server disconnected",
"",
"Failed to (async)export service config: " + interfaceName,
e);
}
},
getDelay(),
TimeUnit.MILLISECONDS);
}
protected void exported() {
exported = true;
List<URL> exportedURLs = this.getExportedUrls();
exportedURLs.forEach(url -> {
if (url.getParameters().containsKey(SERVICE_NAME_MAPPING_KEY)) {
ServiceNameMapping serviceNameMapping = ServiceNameMapping.getDefaultExtension(getScopeModel());
ScheduledExecutorService scheduledExecutor = getScopeModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor();
mapServiceName(url, serviceNameMapping, scheduledExecutor);
}
});
onExported();
}
protected void mapServiceName(
URL url, ServiceNameMapping serviceNameMapping, ScheduledExecutorService scheduledExecutor) {
if (!exported) {
return;
}
logger.info("Try to register interface application mapping for service " + url.getServiceKey());
boolean succeeded = false;
try {
succeeded = serviceNameMapping.map(url);
if (succeeded) {
logger.info("Successfully registered interface application mapping for service " + url.getServiceKey());
} else {
logger.error(
CONFIG_SERVER_DISCONNECTED,
"configuration server disconnected",
"",
"Failed register interface application mapping for service " + url.getServiceKey());
}
} catch (Exception e) {
logger.error(
CONFIG_SERVER_DISCONNECTED,
"configuration server disconnected",
"",
"Failed register interface application mapping for service " + url.getServiceKey(),
e);
}
if (!succeeded && serviceNameMapping.hasValidMetadataCenter()) {
scheduleToMapping(scheduledExecutor, serviceNameMapping, url);
}
}
private void scheduleToMapping(
ScheduledExecutorService scheduledExecutor, ServiceNameMapping serviceNameMapping, URL url) {
Integer mappingRetryInterval = getApplication().getMappingRetryInterval();
scheduledExecutor.schedule(
() -> mapServiceName(url, serviceNameMapping, scheduledExecutor),
mappingRetryInterval == null ? 5000 : mappingRetryInterval,
TimeUnit.MILLISECONDS);
}
private void checkAndUpdateSubConfigs() {
// Use default configs defined explicitly with global scope
completeCompoundConfigs();
checkProtocol();
// init some null configuration.
List<ConfigInitializer> configInitializers = this.getExtensionLoader(ConfigInitializer.class)
.getActivateExtension(URL.valueOf("configInitializer://", getScopeModel()), (String[]) null);
configInitializers.forEach(e -> e.initServiceConfig(this));
// if protocol is not injvm checkRegistry
if (!isOnlyInJvm()) {
checkRegistry();
}
if (StringUtils.isEmpty(interfaceName)) {
throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");
}
if (ref instanceof GenericService) {
interfaceClass = GenericService.class;
if (StringUtils.isEmpty(generic)) {
generic = Boolean.TRUE.toString();
}
} else {
try {
if (getInterfaceClassLoader() != null) {
interfaceClass = Class.forName(interfaceName, true, getInterfaceClassLoader());
} else {
interfaceClass = Class.forName(
interfaceName, true, Thread.currentThread().getContextClassLoader());
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
checkRef();
generic = Boolean.FALSE.toString();
}
if (local != null) {
if ("true".equals(local)) {
local = interfaceName + "Local";
}
Class<?> localClass;
try {
localClass = ClassUtils.forNameWithThreadContextClassLoader(local);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if (!interfaceClass.isAssignableFrom(localClass)) {
throw new IllegalStateException("The local implementation class " + localClass.getName()
+ " not implement interface " + interfaceName);
}
}
if (stub != null) {
if ("true".equals(stub)) {
stub = interfaceName + "Stub";
}
Class<?> stubClass;
try {
stubClass = ClassUtils.forNameWithThreadContextClassLoader(stub);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if (!interfaceClass.isAssignableFrom(stubClass)) {
throw new IllegalStateException("The stub implementation class " + stubClass.getName()
+ " not implement interface " + interfaceName);
}
}
checkStubAndLocal(interfaceClass);
ConfigValidationUtils.checkMock(interfaceClass, this);
ConfigValidationUtils.validateServiceConfig(this);
postProcessConfig();
}
@Override
protected void postProcessRefresh() {
super.postProcessRefresh();
checkAndUpdateSubConfigs();
}
protected synchronized void doExport(RegisterTypeEnum registerType) {
if (unexported) {
throw new IllegalStateException("The service " + interfaceClass.getName() + " has already unexported!");
}
if (exported) {
return;
}
if (StringUtils.isEmpty(path)) {
path = interfaceName;
}
doExportUrls(registerType);
exported();
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void doExportUrls(RegisterTypeEnum registerType) {
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
ServiceDescriptor serviceDescriptor;
final boolean serverService = ref instanceof ServerService;
if (serverService) {
serviceDescriptor = ((ServerService) ref).getServiceDescriptor();
repository.registerService(serviceDescriptor);
} else {
serviceDescriptor = repository.registerService(getInterfaceClass());
}
providerModel = new ProviderModel(
serviceMetadata.getServiceKey(),
ref,
serviceDescriptor,
getScopeModel(),
serviceMetadata,
interfaceClassLoader);
// Compatible with dependencies on ServiceModel#getServiceConfig(), and will be removed in a future version
providerModel.setConfig(this);
providerModel.setDestroyRunner(getDestroyRunner());
repository.registerProvider(providerModel);
List<URL> registryURLs = ConfigValidationUtils.loadRegistries(this, true);
for (ProtocolConfig protocolConfig : protocols) {
String pathKey = URL.buildKey(
getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path), group, version);
// stub service will use generated service name
if (!serverService) {
// In case user specified path, register service one more time to map it to path.
repository.registerService(pathKey, interfaceClass);
}
doExportUrlsFor1Protocol(protocolConfig, registryURLs, registerType);
}
providerModel.setServiceUrls(urls);
}
private void doExportUrlsFor1Protocol(
ProtocolConfig protocolConfig, List<URL> registryURLs, RegisterTypeEnum registerType) {
Map<String, String> map = buildAttributes(protocolConfig);
// remove null key and null value
map.keySet().removeIf(key -> StringUtils.isEmpty(key) || StringUtils.isEmpty(map.get(key)));
// init serviceMetadata attachments
serviceMetadata.getAttachments().putAll(map);
URL url = buildUrl(protocolConfig, map);
processServiceExecutor(url);
exportUrl(url, registryURLs, registerType);
initServiceMethodMetrics(url);
}
private void initServiceMethodMetrics(URL url) {
String[] methods = Optional.ofNullable(url.getParameter(METHODS_KEY))
.map(i -> i.split(","))
.orElse(new String[] {});
boolean serviceLevel = MethodMetric.isServiceLevel(application.getApplicationModel());
Arrays.stream(methods).forEach(method -> {
RpcInvocation invocation = new RpcInvocation(
url.getServiceKey(),
url.getServiceModel(),
method,
interfaceName,
url.getProtocolServiceKey(),
null,
null,
null,
null,
null,
null);
MetricsEventBus.publish(
MetricsInitEvent.toMetricsInitEvent(application.getApplicationModel(), invocation, serviceLevel));
});
}
private void processServiceExecutor(URL url) {
if (getExecutor() != null) {
String mode = application.getExecutorManagementMode();
if (!EXECUTOR_MANAGEMENT_MODE_ISOLATION.equals(mode)) {
logger.warn(
COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR,
"",
"",
"The current executor management mode is " + mode
+ ", the configured service executor cannot take effect unless the mode is configured as "
+ EXECUTOR_MANAGEMENT_MODE_ISOLATION);
return;
}
/**
* Because executor is not a string type, it cannot be attached to the url parameter, so it is added to URL#attributes
* and obtained it in IsolationExecutorRepository#createExecutor method
*/
providerModel.getServiceMetadata().addAttribute(SERVICE_EXECUTOR, getExecutor());
url.getAttributes().put(SERVICE_EXECUTOR, getExecutor());
}
}
private Map<String, String> buildAttributes(ProtocolConfig protocolConfig) {
Map<String, String> map = new HashMap<String, String>();
map.put(SIDE_KEY, PROVIDER_SIDE);
// append params with basic configs,
ServiceConfig.appendRuntimeParameters(map);
AbstractConfig.appendParameters(map, getApplication());
AbstractConfig.appendParameters(map, getModule());
// remove 'default.' prefix for configs from ProviderConfig
// appendParameters(map, provider, Constants.DEFAULT_KEY);
AbstractConfig.appendParameters(map, provider);
AbstractConfig.appendParameters(map, protocolConfig);
AbstractConfig.appendParameters(map, this);
appendMetricsCompatible(map);
// append params with method configs,
if (CollectionUtils.isNotEmpty(getMethods())) {
getMethods().forEach(method -> appendParametersWithMethod(method, map));
}
if (isGeneric(generic)) {
map.put(GENERIC_KEY, generic);
map.put(METHODS_KEY, ANY_VALUE);
} else {
String revision = Version.getVersion(interfaceClass, version);
if (StringUtils.isNotEmpty(revision)) {
map.put(REVISION_KEY, revision);
}
String[] methods = methods(interfaceClass);
if (methods.length == 0) {
logger.warn(
CONFIG_NO_METHOD_FOUND,
"",
"",
"No method found in service interface: " + interfaceClass.getName());
map.put(METHODS_KEY, ANY_VALUE);
} else {
map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR));
}
}
/**
* Here the token value configured by the provider is used to assign the value to ServiceConfig#token
*/
if (ConfigUtils.isEmpty(token) && provider != null) {
token = provider.getToken();
}
if (!ConfigUtils.isEmpty(token)) {
if (ConfigUtils.isDefault(token)) {
map.put(TOKEN_KEY, UUID.randomUUID().toString());
} else {
map.put(TOKEN_KEY, token);
}
}
if (ref instanceof ServerService) {
map.put(PROXY_KEY, CommonConstants.NATIVE_STUB);
}
return map;
}
private void appendParametersWithMethod(MethodConfig method, Map<String, String> params) {
AbstractConfig.appendParameters(params, method, method.getName());
String retryKey = method.getName() + ".retry";
if (params.containsKey(retryKey)) {
String retryValue = params.remove(retryKey);
if ("false".equals(retryValue)) {
params.put(method.getName() + ".retries", "0");
}
}
List<ArgumentConfig> arguments = method.getArguments();
if (CollectionUtils.isNotEmpty(arguments)) {
Method matchedMethod = findMatchedMethod(method);
if (matchedMethod != null) {
arguments.forEach(argument -> appendArgumentConfig(argument, matchedMethod, params));
}
}
}
private Method findMatchedMethod(MethodConfig methodConfig) {
for (Method method : interfaceClass.getMethods()) {
if (method.getName().equals(methodConfig.getName())) {
return method;
}
}
return null;
}
private void appendArgumentConfig(ArgumentConfig argument, Method method, Map<String, String> params) {
if (StringUtils.isNotEmpty(argument.getType())) {
Integer index = findArgumentIndexIndexWithGivenType(argument, method);
AbstractConfig.appendParameters(params, argument, method.getName() + "." + index);
} else if (hasIndex(argument)) {
AbstractConfig.appendParameters(params, argument, method.getName() + "." + argument.getIndex());
} else {
throw new IllegalArgumentException(
"Argument config must set index or type attribute.eg: <dubbo:argument index='0' .../> or <dubbo:argument type=xxx .../>");
}
}
private boolean hasIndex(ArgumentConfig argument) {
return argument.getIndex() != -1;
}
private boolean isTypeMatched(String type, Integer index, Class<?>[] argtypes) {
return index != null
&& index >= 0
&& index < argtypes.length
&& argtypes[index].getName().equals(type);
}
private Integer findArgumentIndexIndexWithGivenType(ArgumentConfig argument, Method method) {
Class<?>[] argTypes = method.getParameterTypes();
// one callback in the method
if (hasIndex(argument)) {
Integer index = argument.getIndex();
String type = argument.getType();
if (isTypeMatched(type, index, argTypes)) {
return index;
} else {
throw new IllegalArgumentException(
"Argument config error : the index attribute and type attribute not match :index :"
+ argument.getIndex() + ", type:" + argument.getType());
}
} else {
// multiple callbacks in the method
for (int j = 0; j < argTypes.length; j++) {
if (isTypeMatched(argument.getType(), j, argTypes)) {
return j;
}
}
throw new IllegalArgumentException(
"Argument config error : no argument matched with the type:" + argument.getType());
}
}
private URL buildUrl(ProtocolConfig protocolConfig, Map<String, String> params) {
String name = protocolConfig.getName();
if (StringUtils.isEmpty(name)) {
name = DUBBO;
}
// export service
String host = findConfiguredHosts(protocolConfig, provider, params);
if (NetUtils.isIPV6URLStdFormat(host)) {
if (!host.contains("[")) {
host = "[" + host + "]";
}
} else if (NetUtils.getLocalHostV6() != null) {
String ipv6Host = NetUtils.getLocalHostV6();
params.put(CommonConstants.IPV6_KEY, ipv6Host);
}
Integer port =
findConfiguredPort(protocolConfig, provider, this.getExtensionLoader(Protocol.class), name, params);
URL url = new ServiceConfigURL(
name,
null,
null,
host,
port,
getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path),
params);
// You can customize Configurator to append extra parameters
if (this.getExtensionLoader(ConfiguratorFactory.class).hasExtension(url.getProtocol())) {
url = this.getExtensionLoader(ConfiguratorFactory.class)
.getExtension(url.getProtocol())
.getConfigurator(url)
.configure(url);
}
url = url.setScopeModel(getScopeModel());
url = url.setServiceModel(providerModel);
return url;
}
private void exportUrl(URL url, List<URL> registryURLs, RegisterTypeEnum registerType) {
String scope = url.getParameter(SCOPE_KEY);
// don't export when none is configured
if (!SCOPE_NONE.equalsIgnoreCase(scope)) {
// export to local if the config is not remote (export to remote only when config is remote)
if (!SCOPE_REMOTE.equalsIgnoreCase(scope)) {
exportLocal(url);
}
// export to remote if the config is not local (export to local only when config is local)
if (!SCOPE_LOCAL.equalsIgnoreCase(scope)) {
// export to extra protocol is used in remote export
String extProtocol = url.getParameter("ext.protocol", "");
List<String> protocols = new ArrayList<>();
if (StringUtils.isNotBlank(extProtocol)) {
// export original url
url = URLBuilder.from(url)
.addParameter(IS_PU_SERVER_KEY, Boolean.TRUE.toString())
.removeParameter("ext.protocol")
.build();
}
url = exportRemote(url, registryURLs, registerType);
if (!isGeneric(generic) && !getScopeModel().isInternal()) {
MetadataUtils.publishServiceDefinition(url, providerModel.getServiceModel(), getApplicationModel());
}
if (StringUtils.isNotBlank(extProtocol)) {
String[] extProtocols = extProtocol.split(",", -1);
protocols.addAll(Arrays.asList(extProtocols));
}
// export extra protocols
for (String protocol : protocols) {
if (StringUtils.isNotBlank(protocol)) {
URL localUrl =
URLBuilder.from(url).setProtocol(protocol).build();
localUrl = exportRemote(localUrl, registryURLs, registerType);
if (!isGeneric(generic) && !getScopeModel().isInternal()) {
MetadataUtils.publishServiceDefinition(
localUrl, providerModel.getServiceModel(), getApplicationModel());
}
this.urls.add(localUrl);
}
}
}
}
this.urls.add(url);
}
private URL exportRemote(URL url, List<URL> registryURLs, RegisterTypeEnum registerType) {
if (CollectionUtils.isNotEmpty(registryURLs) && registerType != RegisterTypeEnum.NEVER_REGISTER) {
for (URL registryURL : registryURLs) {
if (SERVICE_REGISTRY_PROTOCOL.equals(registryURL.getProtocol())) {
url = url.addParameterIfAbsent(SERVICE_NAME_MAPPING_KEY, "true");
}
// if protocol is only injvm ,not register
if (LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
continue;
}
url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY));
URL monitorUrl = ConfigValidationUtils.loadMonitor(this, registryURL);
if (monitorUrl != null) {
url = url.putAttribute(MONITOR_KEY, monitorUrl);
}
// For providers, this is used to enable custom proxy to generate invoker
String proxy = url.getParameter(PROXY_KEY);
if (StringUtils.isNotEmpty(proxy)) {
registryURL = registryURL.addParameter(PROXY_KEY, proxy);
}
if (logger.isInfoEnabled()) {
if (url.getParameter(REGISTER_KEY, true)) {
logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url
+ " to registry " + registryURL.getAddress());
} else {
logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);
}
}
doExportUrl(registryURL.putAttribute(EXPORT_KEY, url), true, registerType);
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);
}
doExportUrl(url, true, registerType);
}
return url;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void doExportUrl(URL url, boolean withMetaData, RegisterTypeEnum registerType) {
if (!url.getParameter(REGISTER_KEY, true)) {
registerType = RegisterTypeEnum.MANUAL_REGISTER;
}
if (registerType == RegisterTypeEnum.NEVER_REGISTER
|| registerType == RegisterTypeEnum.MANUAL_REGISTER
|| registerType == RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER) {
url = url.addParameter(REGISTER_KEY, false);
}
Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url);
if (withMetaData) {
invoker = new DelegateProviderMetaDataInvoker(invoker, this);
}
Exporter<?> exporter = protocolSPI.export(invoker);
exporters
.computeIfAbsent(registerType, k -> new CopyOnWriteArrayList<>())
.add(exporter);
}
/**
* always export injvm
*/
private void exportLocal(URL url) {
URL local = URLBuilder.from(url)
.setProtocol(LOCAL_PROTOCOL)
.setHost(LOCALHOST_VALUE)
.setPort(0)
.build();
local = local.setScopeModel(getScopeModel()).setServiceModel(providerModel);
local = local.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL);
doExportUrl(local, false, RegisterTypeEnum.AUTO_REGISTER);
logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry url : " + local);
}
/**
* Determine if it is injvm
*
* @return
*/
private boolean isOnlyInJvm() {
return getProtocols().size() == 1
&& LOCAL_PROTOCOL.equalsIgnoreCase(getProtocols().get(0).getName());
}
private void postProcessConfig() {
List<ConfigPostProcessor> configPostProcessors = this.getExtensionLoader(ConfigPostProcessor.class)
.getActivateExtension(URL.valueOf("configPostProcessor://", getScopeModel()), (String[]) null);
configPostProcessors.forEach(component -> component.postProcessServiceConfig(this));
}
public void addServiceListener(ServiceListener listener) {
this.serviceListeners.add(listener);
}
protected void onExported() {
for (ServiceListener serviceListener : this.serviceListeners) {
serviceListener.exported(this);
}
}
protected void onUnexpoted() {
for (ServiceListener serviceListener : this.serviceListeners) {
serviceListener.unexported(this);
}
}
/**
* Register & bind IP address for service provider, can be configured separately.
* Configuration priority: environment variables -> java system properties -> host property in config file ->
* /etc/hosts -> default network address -> first available network address
*
* @param protocolConfig
* @param map
* @return
*/
private static String findConfiguredHosts(
ProtocolConfig protocolConfig, ProviderConfig provider, Map<String, String> map) {
boolean anyhost = false;
String hostToBind = getValueFromConfig(protocolConfig, DUBBO_IP_TO_BIND);
if (StringUtils.isNotEmpty(hostToBind) && isInvalidLocalHost(hostToBind)) {
throw new IllegalArgumentException(
"Specified invalid bind ip from property:" + DUBBO_IP_TO_BIND + ", value:" + hostToBind);
}
// if bind ip is not found in environment, keep looking up
if (StringUtils.isEmpty(hostToBind)) {
hostToBind = protocolConfig.getHost();
if (provider != null && StringUtils.isEmpty(hostToBind)) {
hostToBind = provider.getHost();
}
if (isInvalidLocalHost(hostToBind)) {
anyhost = true;
if (logger.isDebugEnabled()) {
logger.debug("No valid ip found from environment, try to get local host.");
}
hostToBind = getLocalHost();
}
}
map.put(BIND_IP_KEY, hostToBind);
// bind ip is not used for registry ip by default
String hostToRegistry = getValueFromConfig(protocolConfig, DUBBO_IP_TO_REGISTRY);
if (StringUtils.isNotEmpty(hostToRegistry) && isInvalidLocalHost(hostToRegistry)) {
throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY
+ ", value:" + hostToRegistry);
} else if (StringUtils.isEmpty(hostToRegistry)) {
// bind ip is used as registry ip by default
hostToRegistry = hostToBind;
}
map.put(ANYHOST_KEY, String.valueOf(anyhost));
return hostToRegistry;
}
/**
* Register port and bind port for the provider, can be configured separately
* Configuration priority: environment variable -> java system properties -> port property in protocol config file
* -> protocol default port
*
* @param protocolConfig
* @param name
* @return
*/
private static synchronized Integer findConfiguredPort(
ProtocolConfig protocolConfig,
ProviderConfig provider,
ExtensionLoader<Protocol> extensionLoader,
String name,
Map<String, String> map) {
Integer portToBind;
// parse bind port from environment
String port = getValueFromConfig(protocolConfig, DUBBO_PORT_TO_BIND);
portToBind = parsePort(port);
// if there's no bind port found from environment, keep looking up.
if (portToBind == null) {
portToBind = protocolConfig.getPort();
if (provider != null && (portToBind == null || portToBind == 0)) {
portToBind = provider.getPort();
}
final int defaultPort = extensionLoader.getExtension(name).getDefaultPort();
if (portToBind == null || portToBind == 0) {
portToBind = defaultPort;
}
if (portToBind <= 0) {
portToBind = getRandomPort(name);
if (portToBind == null || portToBind < 0) {
portToBind = getAvailablePort(defaultPort);
putRandomPort(name, portToBind);
}
}
}
// save bind port, used as url's key later
map.put(BIND_PORT_KEY, String.valueOf(portToBind));
// bind port is not used as registry port by default
String portToRegistryStr = getValueFromConfig(protocolConfig, DUBBO_PORT_TO_REGISTRY);
Integer portToRegistry = parsePort(portToRegistryStr);
if (portToRegistry == null) {
portToRegistry = portToBind;
}
return portToRegistry;
}
private static Integer parsePort(String configPort) {
Integer port = null;
if (StringUtils.isNotEmpty(configPort)) {
try {
int intPort = Integer.parseInt(configPort);
if (isInvalidPort(intPort)) {
throw new IllegalArgumentException("Specified invalid port from env value:" + configPort);
}
port = intPort;
} catch (Exception e) {
throw new IllegalArgumentException("Specified invalid port from env value:" + configPort);
}
}
return port;
}
private static String getValueFromConfig(ProtocolConfig protocolConfig, String key) {
String protocolPrefix = protocolConfig.getName().toUpperCase() + "_";
String value = ConfigUtils.getSystemProperty(protocolPrefix + key);
if (StringUtils.isEmpty(value)) {
value = ConfigUtils.getSystemProperty(key);
}
return value;
}
private static Integer getRandomPort(String protocol) {
protocol = protocol.toLowerCase();
return RANDOM_PORT_MAP.getOrDefault(protocol, Integer.MIN_VALUE);
}
private static void putRandomPort(String protocol, Integer port) {
protocol = protocol.toLowerCase();
if (!RANDOM_PORT_MAP.containsKey(protocol)) {
RANDOM_PORT_MAP.put(protocol, port);
logger.warn(
CONFIG_USE_RANDOM_PORT, "", "", "Use random available port(" + port + ") for protocol " + protocol);
}
}
@Transient
public Runnable getDestroyRunner() {
return this::unexport;
}
}
| 8,575 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* Dynamically add some parameters / check config
*/
@SPI(scope = ExtensionScope.MODULE)
public interface ConfigInitializer {
default void initReferConfig(ReferenceConfig referenceConfig) {}
default void initServiceConfig(ServiceConfig serviceConfig) {}
}
| 8,576 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.SPI;
/**
* Listener for service config
*/
@SPI
public interface ServiceListener {
/**
* Callback when ServiceConfig is exported
* @param sc
*/
void exported(ServiceConfig sc);
/**
* Callback when ServiceConfig is unexported
* @param sc
*/
void unexported(ServiceConfig sc);
}
| 8,577 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.config.deploy.DefaultApplicationDeployer;
import org.apache.dubbo.config.deploy.DefaultModuleDeployer;
import org.apache.dubbo.config.deploy.FrameworkModelCleaner;
import org.apache.dubbo.config.utils.DefaultConfigValidator;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class ConfigScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
frameworkModel.addDestroyListener(new FrameworkModelCleaner());
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(DefaultConfigValidator.class);
// applicationDeployer
ApplicationDeployer applicationDeployer = beanFactory.registerBean(DefaultApplicationDeployer.class);
applicationModel.setDeployer(applicationDeployer);
}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {
ScopeBeanFactory beanFactory = moduleModel.getBeanFactory();
// moduleDeployer
ModuleDeployer moduleDeployer = beanFactory.registerBean(DefaultModuleDeployer.class);
moduleModel.setDeployer(moduleDeployer);
}
}
| 8,578 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.ArrayUtils;
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.annotation.Reference;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.cluster.support.registry.ZoneAwareCluster;
import org.apache.dubbo.rpc.model.AsyncMethodInfo;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.DubboStub;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.injvm.InjvmProtocol;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.stub.StubSuppliers;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLUSTER_DOMAIN;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_MESH_PORT;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.MESH_ENABLE;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROXY_CLASS_REF;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SVC;
import static org.apache.dubbo.common.constants.CommonConstants.TRIPLE;
import static org.apache.dubbo.common.constants.CommonConstants.UNLOAD_CLUSTER_RELATED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_VALID_PROVIDER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_DESTROY_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_METHOD_FOUND;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PROPERTY_CONFLICT;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost;
import static org.apache.dubbo.common.utils.StringUtils.splitToSet;
import static org.apache.dubbo.config.Constants.DUBBO_IP_TO_REGISTRY;
import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
/**
* Please avoid using this class for any new application,
* use {@link ReferenceConfigBase} instead.
*/
public class ReferenceConfig<T> extends ReferenceConfigBase<T> {
public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceConfig.class);
/**
* The {@link Protocol} implementation with adaptive functionality,it will be different in different scenarios.
* A particular {@link Protocol} implementation is determined by the protocol attribute in the {@link URL}.
* For example:
*
* <li>when the url is registry://224.5.6.7:1234/org.apache.dubbo.registry.RegistryService?application=dubbo-sample,
* then the protocol is <b>RegistryProtocol</b></li>
*
* <li>when the url is dubbo://224.5.6.7:1234/org.apache.dubbo.config.api.DemoService?application=dubbo-sample, then
* the protocol is <b>DubboProtocol</b></li>
* <p>
* Actually,when the {@link ExtensionLoader} init the {@link Protocol} instants,it will automatically wrap three
* layers, and eventually will get a <b>ProtocolSerializationWrapper</b> or <b>ProtocolFilterWrapper</b> or <b>ProtocolListenerWrapper</b>
*/
private Protocol protocolSPI;
/**
* A {@link ProxyFactory} implementation that will generate a reference service's proxy,the JavassistProxyFactory is
* its default implementation
*/
private ProxyFactory proxyFactory;
private ConsumerModel consumerModel;
/**
* The interface proxy reference
*/
private transient volatile T ref;
/**
* The invoker of the reference service
*/
private transient volatile Invoker<?> invoker;
/**
* The flag whether the ReferenceConfig has been initialized
*/
private transient volatile boolean initialized;
/**
* whether this ReferenceConfig has been destroyed
*/
private transient volatile boolean destroyed;
/**
* The service names that the Dubbo interface subscribed.
*
* @since 2.7.8
*/
private String services;
public ReferenceConfig() {
super();
}
public ReferenceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
public ReferenceConfig(Reference reference) {
super(reference);
}
public ReferenceConfig(ModuleModel moduleModel, Reference reference) {
super(moduleModel, reference);
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
protocolSPI = this.getExtensionLoader(Protocol.class).getAdaptiveExtension();
proxyFactory = this.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
}
/**
* Get a string presenting the service names that the Dubbo interface subscribed.
* If it is a multiple-values, the content will be a comma-delimited String.
*
* @return non-null
* @see RegistryConstants#SUBSCRIBED_SERVICE_NAMES_KEY
* @since 2.7.8
*/
@Deprecated
@Parameter(key = SUBSCRIBED_SERVICE_NAMES_KEY)
public String getServices() {
return services;
}
/**
* It's an alias method for {@link #getServices()}, but the more convenient.
*
* @return the String {@link List} presenting the Dubbo interface subscribed
* @since 2.7.8
*/
@Deprecated
@Parameter(excluded = true)
public Set<String> getSubscribedServices() {
return splitToSet(getServices(), COMMA_SEPARATOR_CHAR);
}
/**
* Set the service names that the Dubbo interface subscribed.
*
* @param services If it is a multiple-values, the content will be a comma-delimited String.
* @since 2.7.8
*/
public void setServices(String services) {
this.services = services;
}
@Override
@Transient
public T get(boolean check) {
if (destroyed) {
throw new IllegalStateException("The invoker of ReferenceConfig(" + url + ") has already destroyed!");
}
if (ref == null) {
if (getScopeModel().isLifeCycleManagedExternally()) {
// prepare model for reference
getScopeModel().getDeployer().prepare();
} else {
// ensure start module, compatible with old api usage
getScopeModel().getDeployer().start();
}
init(check);
}
return ref;
}
@Override
public void checkOrDestroy(long timeout) {
if (!initialized || ref == null) {
return;
}
try {
checkInvokerAvailable(timeout);
} catch (Throwable t) {
logAndCleanup(t);
throw t;
}
}
private void logAndCleanup(Throwable t) {
try {
if (invoker != null) {
invoker.destroy();
}
} catch (Throwable destroy) {
logger.warn(
CONFIG_FAILED_DESTROY_INVOKER,
"",
"",
"Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").",
t);
}
if (consumerModel != null) {
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
repository.unregisterConsumer(consumerModel);
}
initialized = false;
invoker = null;
ref = null;
consumerModel = null;
serviceMetadata.setTarget(null);
serviceMetadata.getAttributeMap().remove(PROXY_CLASS_REF);
// Thrown by checkInvokerAvailable().
if (t.getClass() == IllegalStateException.class
&& t.getMessage().contains("No provider available for the service")) {
// 2-2 - No provider available.
logger.error(CLUSTER_NO_VALID_PROVIDER, "server crashed", "", "No provider available.", t);
}
}
@Override
public synchronized void destroy() {
super.destroy();
if (destroyed) {
return;
}
destroyed = true;
try {
if (invoker != null) {
invoker.destroy();
}
} catch (Throwable t) {
logger.warn(
CONFIG_FAILED_DESTROY_INVOKER,
"",
"",
"Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").",
t);
}
invoker = null;
ref = null;
if (consumerModel != null) {
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
repository.unregisterConsumer(consumerModel);
}
}
protected synchronized void init() {
init(true);
}
protected synchronized void init(boolean check) {
if (initialized && ref != null) {
return;
}
try {
if (!this.isRefreshed()) {
this.refresh();
}
// auto detect proxy type
String proxyType = getProxy();
if (StringUtils.isBlank(proxyType) && DubboStub.class.isAssignableFrom(interfaceClass)) {
setProxy(CommonConstants.NATIVE_STUB);
}
// init serviceMetadata
initServiceMetadata(consumer);
serviceMetadata.setServiceType(getServiceInterfaceClass());
// TODO, uncomment this line once service key is unified
serviceMetadata.generateServiceKey();
Map<String, String> referenceParameters = appendConfig();
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
ServiceDescriptor serviceDescriptor;
if (CommonConstants.NATIVE_STUB.equals(getProxy())) {
serviceDescriptor = StubSuppliers.getServiceDescriptor(interfaceName);
repository.registerService(serviceDescriptor);
} else {
serviceDescriptor = repository.registerService(interfaceClass);
}
consumerModel = new ConsumerModel(
serviceMetadata.getServiceKey(),
proxy,
serviceDescriptor,
getScopeModel(),
serviceMetadata,
createAsyncMethodInfo(),
interfaceClassLoader);
// Compatible with dependencies on ServiceModel#getReferenceConfig() , and will be removed in a future
// version.
consumerModel.setConfig(this);
repository.registerConsumer(consumerModel);
serviceMetadata.getAttachments().putAll(referenceParameters);
ref = createProxy(referenceParameters);
serviceMetadata.setTarget(ref);
serviceMetadata.addAttribute(PROXY_CLASS_REF, ref);
consumerModel.setDestroyRunner(getDestroyRunner());
consumerModel.setProxyObject(ref);
consumerModel.initMethodModels();
if (check) {
checkInvokerAvailable(0);
}
} catch (Throwable t) {
logAndCleanup(t);
throw t;
}
initialized = true;
}
/**
* convert and aggregate async method info
*
* @return Map<String, AsyncMethodInfo>
*/
private Map<String, AsyncMethodInfo> createAsyncMethodInfo() {
Map<String, AsyncMethodInfo> attributes = null;
if (CollectionUtils.isNotEmpty(getMethods())) {
attributes = new HashMap<>(16);
for (MethodConfig methodConfig : getMethods()) {
AsyncMethodInfo asyncMethodInfo = methodConfig.convertMethodConfig2AsyncInfo();
if (asyncMethodInfo != null) {
attributes.put(methodConfig.getName(), asyncMethodInfo);
}
}
}
return attributes;
}
/**
* Append all configuration required for service reference.
*
* @return reference parameters
*/
private Map<String, String> appendConfig() {
Map<String, String> map = new HashMap<>(16);
map.put(INTERFACE_KEY, interfaceName);
map.put(SIDE_KEY, CONSUMER_SIDE);
ReferenceConfigBase.appendRuntimeParameters(map);
if (!ProtocolUtils.isGeneric(generic)) {
String revision = Version.getVersion(interfaceClass, version);
if (StringUtils.isNotEmpty(revision)) {
map.put(REVISION_KEY, revision);
}
String[] methods = methods(interfaceClass);
if (methods.length == 0) {
logger.warn(
CONFIG_NO_METHOD_FOUND,
"",
"",
"No method found in service interface: " + interfaceClass.getName());
map.put(METHODS_KEY, ANY_VALUE);
} else {
map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR));
}
}
AbstractConfig.appendParameters(map, getApplication());
AbstractConfig.appendParameters(map, getModule());
AbstractConfig.appendParameters(map, consumer);
AbstractConfig.appendParameters(map, this);
appendMetricsCompatible(map);
String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
if (StringUtils.isEmpty(hostToRegistry)) {
hostToRegistry = NetUtils.getLocalHost();
} else if (isInvalidLocalHost(hostToRegistry)) {
throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY
+ ", value:" + hostToRegistry);
}
map.put(REGISTER_IP_KEY, hostToRegistry);
if (CollectionUtils.isNotEmpty(getMethods())) {
for (MethodConfig methodConfig : getMethods()) {
AbstractConfig.appendParameters(map, methodConfig, methodConfig.getName());
String retryKey = methodConfig.getName() + ".retry";
if (map.containsKey(retryKey)) {
String retryValue = map.remove(retryKey);
if ("false".equals(retryValue)) {
map.put(methodConfig.getName() + ".retries", "0");
}
}
}
}
return map;
}
@SuppressWarnings({"unchecked"})
private T createProxy(Map<String, String> referenceParameters) {
urls.clear();
meshModeHandleUrl(referenceParameters);
if (StringUtils.isNotEmpty(url)) {
// user specified URL, could be peer-to-peer address, or register center's address.
parseUrl(referenceParameters);
} else {
// if protocols not in jvm checkRegistry
aggregateUrlFromRegistry(referenceParameters);
}
createInvoker();
if (logger.isInfoEnabled()) {
logger.info("Referred dubbo service: [" + referenceParameters.get(INTERFACE_KEY) + "]."
+ (ProtocolUtils.isGeneric(referenceParameters.get(GENERIC_KEY))
? " it's GenericService reference"
: " it's not GenericService reference"));
}
URL consumerUrl = new ServiceConfigURL(
CONSUMER_PROTOCOL,
referenceParameters.get(REGISTER_IP_KEY),
0,
referenceParameters.get(INTERFACE_KEY),
referenceParameters);
consumerUrl = consumerUrl.setScopeModel(getScopeModel());
consumerUrl = consumerUrl.setServiceModel(consumerModel);
MetadataUtils.publishServiceDefinition(consumerUrl, consumerModel.getServiceModel(), getApplicationModel());
// create service proxy
return (T) proxyFactory.getProxy(invoker, ProtocolUtils.isGeneric(generic));
}
/**
* if enable mesh mode, handle url.
*
* @param referenceParameters referenceParameters
*/
private void meshModeHandleUrl(Map<String, String> referenceParameters) {
if (!checkMeshConfig(referenceParameters)) {
return;
}
if (StringUtils.isNotEmpty(url)) {
// user specified URL, could be peer-to-peer address, or register center's address.
if (logger.isInfoEnabled()) {
logger.info("The url already exists, mesh no longer processes url: " + url);
}
return;
}
// get provider namespace if (@DubboReference, <reference provider-namespace="xx"/>) present
String podNamespace = referenceParameters.get(RegistryConstants.PROVIDER_NAMESPACE);
// get pod namespace from env if annotation not present the provider namespace
if (StringUtils.isEmpty(podNamespace)) {
if (StringUtils.isEmpty(System.getenv("POD_NAMESPACE"))) {
if (logger.isWarnEnabled()) {
logger.warn(
CONFIG_FAILED_LOAD_ENV_VARIABLE,
"",
"",
"Can not get env variable: POD_NAMESPACE, it may not be running in the K8S environment , "
+ "finally use 'default' replace.");
}
podNamespace = "default";
} else {
podNamespace = System.getenv("POD_NAMESPACE");
}
}
// In mesh mode, providedBy equals K8S Service name.
String providedBy = referenceParameters.get(PROVIDED_BY);
// cluster_domain default is 'cluster.local',generally unchanged.
String clusterDomain =
Optional.ofNullable(System.getenv("CLUSTER_DOMAIN")).orElse(DEFAULT_CLUSTER_DOMAIN);
// By VirtualService and DestinationRule, envoy will generate a new route rule,such as
// 'demo.default.svc.cluster.local:80',the default port is 80.
Integer meshPort = Optional.ofNullable(getProviderPort()).orElse(DEFAULT_MESH_PORT);
// DubboReference default is -1, process it.
meshPort = meshPort > -1 ? meshPort : DEFAULT_MESH_PORT;
// get mesh url.
url = TRIPLE + "://" + providedBy + "." + podNamespace + SVC + clusterDomain + ":" + meshPort;
}
/**
* check if mesh config is correct
*
* @param referenceParameters referenceParameters
* @return mesh config is correct
*/
private boolean checkMeshConfig(Map<String, String> referenceParameters) {
if (!"true".equals(referenceParameters.getOrDefault(MESH_ENABLE, "false"))) {
// In mesh mode, unloadClusterRelated can only be false.
referenceParameters.put(UNLOAD_CLUSTER_RELATED, "false");
return false;
}
getScopeModel()
.getConfigManager()
.getProtocol(TRIPLE)
.orElseThrow(() -> new IllegalStateException("In mesh mode, a triple protocol must be specified"));
String providedBy = referenceParameters.get(PROVIDED_BY);
if (StringUtils.isEmpty(providedBy)) {
throw new IllegalStateException("In mesh mode, the providedBy of ReferenceConfig is must be set");
}
return true;
}
/**
* Parse the directly configured url.
*/
private void parseUrl(Map<String, String> referenceParameters) {
String[] us = SEMICOLON_SPLIT_PATTERN.split(url);
if (ArrayUtils.isNotEmpty(us)) {
for (String u : us) {
URL url = URL.valueOf(u);
if (StringUtils.isEmpty(url.getPath())) {
url = url.setPath(interfaceName);
}
url = url.setScopeModel(getScopeModel());
url = url.setServiceModel(consumerModel);
if (UrlUtils.isRegistry(url)) {
urls.add(url.putAttribute(REFER_KEY, referenceParameters));
} else {
URL peerUrl = getScopeModel()
.getApplicationModel()
.getBeanFactory()
.getBean(ClusterUtils.class)
.mergeUrl(url, referenceParameters);
peerUrl = peerUrl.putAttribute(PEER_KEY, true);
urls.add(peerUrl);
}
}
}
}
/**
* Get URLs from the registry and aggregate them.
*/
private void aggregateUrlFromRegistry(Map<String, String> referenceParameters) {
checkRegistry();
List<URL> us = ConfigValidationUtils.loadRegistries(this, false);
if (CollectionUtils.isNotEmpty(us)) {
for (URL u : us) {
URL monitorUrl = ConfigValidationUtils.loadMonitor(this, u);
if (monitorUrl != null) {
u = u.putAttribute(MONITOR_KEY, monitorUrl);
}
u = u.setScopeModel(getScopeModel());
u = u.setServiceModel(consumerModel);
if (isInjvm() != null && isInjvm()) {
u = u.addParameter(LOCAL_PROTOCOL, true);
}
urls.add(u.putAttribute(REFER_KEY, referenceParameters));
}
}
if (urls.isEmpty() && shouldJvmRefer(referenceParameters)) {
URL injvmUrl = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName())
.addParameters(referenceParameters);
injvmUrl = injvmUrl.setScopeModel(getScopeModel());
injvmUrl = injvmUrl.setServiceModel(consumerModel);
urls.add(injvmUrl.putAttribute(REFER_KEY, referenceParameters));
}
if (urls.isEmpty()) {
throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer "
+ NetUtils.getLocalHost() + " use dubbo version "
+ Version.getVersion()
+ ", please config <dubbo:registry address=\"...\" /> to your spring config.");
}
}
/**
* \create a reference invoker
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void createInvoker() {
if (urls.size() == 1) {
URL curUrl = urls.get(0);
invoker = protocolSPI.refer(interfaceClass, curUrl);
// registry url, mesh-enable and unloadClusterRelated is true, not need Cluster.
if (!UrlUtils.isRegistry(curUrl) && !curUrl.getParameter(UNLOAD_CLUSTER_RELATED, false)) {
List<Invoker<?>> invokers = new ArrayList<>();
invokers.add(invoker);
invoker = Cluster.getCluster(getScopeModel(), Cluster.DEFAULT)
.join(new StaticDirectory(curUrl, invokers), true);
}
} else {
List<Invoker<?>> invokers = new ArrayList<>();
URL registryUrl = null;
for (URL url : urls) {
// For multi-registry scenarios, it is not checked whether each referInvoker is available.
// Because this invoker may become available later.
invokers.add(protocolSPI.refer(interfaceClass, url));
if (UrlUtils.isRegistry(url)) {
// use last registry url
registryUrl = url;
}
}
if (registryUrl != null) {
// registry url is available
// for multi-subscription scenario, use 'zone-aware' policy by default
String cluster = registryUrl.getParameter(CLUSTER_KEY, ZoneAwareCluster.NAME);
// The invoker wrap sequence would be: ZoneAwareClusterInvoker(StaticDirectory) ->
// FailoverClusterInvoker
// (RegistryDirectory, routing happens here) -> Invoker
invoker = Cluster.getCluster(registryUrl.getScopeModel(), cluster, false)
.join(new StaticDirectory(registryUrl, invokers), false);
} else {
// not a registry url, must be direct invoke.
if (CollectionUtils.isEmpty(invokers)) {
throw new IllegalArgumentException("invokers == null");
}
URL curUrl = invokers.get(0).getUrl();
String cluster = curUrl.getParameter(CLUSTER_KEY, Cluster.DEFAULT);
invoker =
Cluster.getCluster(getScopeModel(), cluster).join(new StaticDirectory(curUrl, invokers), true);
}
}
}
private void checkInvokerAvailable(long timeout) throws IllegalStateException {
if (!shouldCheck()) {
return;
}
boolean available = invoker.isAvailable();
if (available) {
return;
}
long startTime = System.currentTimeMillis();
long checkDeadline = startTime + timeout;
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
available = invoker.isAvailable();
} while (!available && checkDeadline > System.currentTimeMillis());
logger.warn(
LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS,
"",
"",
"Check reference of [" + getUniqueServiceName() + "] failed very beginning. " + "After "
+ (System.currentTimeMillis() - startTime) + "ms reties, finally "
+ (available ? "succeed" : "failed")
+ ".");
if (!available) {
// 2-2 - No provider available.
IllegalStateException illegalStateException =
new IllegalStateException("Failed to check the status of the service "
+ interfaceName
+ ". No provider available for the service "
+ (group == null ? "" : group + "/")
+ interfaceName + (version == null ? "" : ":" + version)
+ " from the url "
+ invoker.getUrl()
+ " to the consumer "
+ NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion());
logger.error(
CLUSTER_NO_VALID_PROVIDER,
"provider not started",
"",
"No provider available.",
illegalStateException);
throw illegalStateException;
}
}
/**
* This method should be called right after the creation of this class's instance, before any property in other config modules is used.
* Check each config modules are created properly and override their properties if necessary.
*/
protected void checkAndUpdateSubConfigs() {
if (StringUtils.isEmpty(interfaceName)) {
throw new IllegalStateException("<dubbo:reference interface=\"\" /> interface not allow null!");
}
// get consumer's global configuration
completeCompoundConfigs();
// init some null configuration.
List<ConfigInitializer> configInitializers = this.getExtensionLoader(ConfigInitializer.class)
.getActivateExtension(URL.valueOf("configInitializer://"), (String[]) null);
configInitializers.forEach(e -> e.initReferConfig(this));
if (getGeneric() == null && getConsumer() != null) {
setGeneric(getConsumer().getGeneric());
}
if (ProtocolUtils.isGeneric(generic)) {
if (interfaceClass != null && !interfaceClass.equals(GenericService.class)) {
logger.warn(
CONFIG_PROPERTY_CONFLICT,
"",
"",
String.format(
"Found conflicting attributes for interface type: [interfaceClass=%s] and [generic=%s], "
+ "because the 'generic' attribute has higher priority than 'interfaceClass', so change 'interfaceClass' to '%s'. "
+ "Note: it will make this reference bean as a candidate bean of type '%s' instead of '%s' when resolving dependency in Spring.",
interfaceClass.getName(),
generic,
GenericService.class.getName(),
GenericService.class.getName(),
interfaceClass.getName()));
}
interfaceClass = GenericService.class;
} else {
try {
if (getInterfaceClassLoader() != null
&& (interfaceClass == null || interfaceClass.getClassLoader() != getInterfaceClassLoader())) {
interfaceClass = Class.forName(interfaceName, true, getInterfaceClassLoader());
} else if (interfaceClass == null) {
interfaceClass = Class.forName(
interfaceName, true, Thread.currentThread().getContextClassLoader());
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
checkStubAndLocal(interfaceClass);
ConfigValidationUtils.checkMock(interfaceClass, this);
if (StringUtils.isEmpty(url)) {
checkRegistry();
}
resolveFile();
ConfigValidationUtils.validateReferenceConfig(this);
postProcessConfig();
}
@Override
protected void postProcessRefresh() {
super.postProcessRefresh();
checkAndUpdateSubConfigs();
}
protected void completeCompoundConfigs() {
super.completeCompoundConfigs(consumer);
if (consumer != null) {
if (StringUtils.isEmpty(registryIds)) {
setRegistryIds(consumer.getRegistryIds());
}
}
}
/**
* Figure out should refer the service in the same JVM from configurations. The default behavior is true
* 1. if injvm is specified, then use it
* 2. then if a url is specified, then assume it's a remote call
* 3. otherwise, check scope parameter
* 4. if scope is not specified but the target service is provided in the same JVM, then prefer to make the local
* call, which is the default behavior
*/
protected boolean shouldJvmRefer(Map<String, String> map) {
boolean isJvmRefer;
if (isInjvm() == null) {
// if an url is specified, don't do local reference
if (StringUtils.isNotEmpty(url)) {
isJvmRefer = false;
} else {
// by default, reference local service if there is
URL tmpUrl = new ServiceConfigURL("temp", "localhost", 0, map);
isJvmRefer = InjvmProtocol.getInjvmProtocol(getScopeModel()).isInjvmRefer(tmpUrl);
}
} else {
isJvmRefer = isInjvm();
}
return isJvmRefer;
}
private void postProcessConfig() {
List<ConfigPostProcessor> configPostProcessors = this.getExtensionLoader(ConfigPostProcessor.class)
.getActivateExtension(URL.valueOf("configPostProcessor://"), (String[]) null);
configPostProcessors.forEach(component -> component.postProcessReferConfig(this));
}
/**
* Return if ReferenceConfig has been initialized
* Note: Cannot use `isInitilized` as it may be treated as a Java Bean property
*
* @return initialized
*/
@Transient
public boolean configInitialized() {
return initialized;
}
/**
* just for test
*
* @return
*/
@Deprecated
@Transient
public Invoker<?> getInvoker() {
return invoker;
}
@Transient
public Runnable getDestroyRunner() {
return this::destroy;
}
}
| 8,579 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* 2019/12/30
*/
@SPI(scope = ExtensionScope.MODULE)
public interface ConfigPostProcessor {
default void postProcessReferConfig(ReferenceConfig referenceConfig) {}
default void postProcessServiceConfig(ServiceConfig serviceConfig) {}
}
| 8,580 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.rpc.GracefulShutdown;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_SHUTDOWN_HOOK;
/**
* The shutdown hook thread to do the cleanup stuff.
* This is a singleton in order to ensure there is only one shutdown hook registered.
* Because {@link ApplicationShutdownHooks} use {@link java.util.IdentityHashMap}
* to store the shutdown hooks.
*/
public class DubboShutdownHook extends Thread {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboShutdownHook.class);
private final ApplicationModel applicationModel;
/**
* Has it already been registered or not?
*/
private final AtomicBoolean registered = new AtomicBoolean(false);
/**
* Has it already been destroyed or not?
*/
private final AtomicBoolean destroyed = new AtomicBoolean(false);
/**
* Whether ignore listen on shutdown hook?
*/
private final boolean ignoreListenShutdownHook;
public DubboShutdownHook(ApplicationModel applicationModel) {
super("DubboShutdownHook");
this.applicationModel = applicationModel;
Assert.notNull(this.applicationModel, "ApplicationModel is null");
ignoreListenShutdownHook = Boolean.parseBoolean(
ConfigurationUtils.getProperty(applicationModel, CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK));
if (ignoreListenShutdownHook) {
logger.info(
CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK + " configured, will ignore add shutdown hook to jvm.");
}
}
@Override
public void run() {
if (!ignoreListenShutdownHook && destroyed.compareAndSet(false, true)) {
if (logger.isInfoEnabled()) {
logger.info("Run shutdown hook now.");
}
doDestroy();
}
}
private void doDestroy() {
int timeout = ConfigurationUtils.getServerShutdownTimeout(applicationModel);
ConfigurationUtils.setExpectedShutdownTime(System.currentTimeMillis() + timeout);
// send readonly for shutdown hook
List<GracefulShutdown> gracefulShutdowns =
GracefulShutdown.getGracefulShutdowns(applicationModel.getFrameworkModel());
for (GracefulShutdown gracefulShutdown : gracefulShutdowns) {
gracefulShutdown.readonly();
}
boolean hasModuleBindSpring = false;
// check if any modules are bound to Spring
for (ModuleModel module : applicationModel.getModuleModels()) {
if (module.isLifeCycleManagedExternally()) {
hasModuleBindSpring = true;
break;
}
}
if (hasModuleBindSpring) {
if (timeout > 0) {
long start = System.currentTimeMillis();
/*
To avoid shutdown conflicts between Dubbo and Spring,
wait for the modules bound to Spring to be handled by Spring until timeout.
*/
logger.info(
"Waiting for modules(" + applicationModel.getDesc() + ") managed by Spring to be shutdown.");
while (!applicationModel.isDestroyed()
&& hasModuleBindSpring
&& (System.currentTimeMillis() - start) < timeout) {
try {
TimeUnit.MILLISECONDS.sleep(10);
hasModuleBindSpring = false;
if (!applicationModel.isDestroyed()) {
for (ModuleModel module : applicationModel.getModuleModels()) {
if (module.isLifeCycleManagedExternally()) {
hasModuleBindSpring = true;
break;
}
}
}
} catch (InterruptedException e) {
logger.warn(LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", e.getMessage(), e);
Thread.currentThread().interrupt();
}
}
if (!applicationModel.isDestroyed()) {
long usage = System.currentTimeMillis() - start;
logger.info("Dubbo wait for application(" + applicationModel.getDesc()
+ ") managed by Spring to be shutdown failed, " + "time usage: " + usage + "ms");
}
}
}
if (!applicationModel.isDestroyed()) {
logger.info("Dubbo shutdown hooks execute now. " + applicationModel.getDesc());
applicationModel.destroy();
}
}
/**
* Register the ShutdownHook
*/
public void register() {
if (!ignoreListenShutdownHook && registered.compareAndSet(false, true)) {
try {
Runtime.getRuntime().addShutdownHook(this);
} catch (IllegalStateException e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "register shutdown hook failed: " + e.getMessage(), e);
} catch (Exception e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "register shutdown hook failed: " + e.getMessage(), e);
}
}
}
/**
* Unregister the ShutdownHook
*/
public void unregister() {
if (!ignoreListenShutdownHook && registered.compareAndSet(true, false)) {
if (this.isAlive()) {
// DubboShutdownHook thread is running
return;
}
try {
Runtime.getRuntime().removeShutdownHook(this);
} catch (IllegalStateException e) {
logger.warn(
CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e);
} catch (Exception e) {
logger.warn(
CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e);
}
}
}
public boolean getRegistered() {
return registered.get();
}
}
| 8,581 |
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/bootstrap/DubboBootstrapStartStopListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.extension.SPI;
/**
* call on DubboBootstrap start or stop.
*
* @scene 2.7.9
* @see DubboBootstrap
*/
@SPI
@Deprecated
public interface DubboBootstrapStartStopListener {
void onStart(DubboBootstrap bootstrap);
void onStop(DubboBootstrap bootstrap);
}
| 8,582 |
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/bootstrap/BootstrapTakeoverMode.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.config.ServiceConfig;
/**
* Mode of which of DubboBootstrap lifecycle being takeover
* SPRING: will be controlled by spring context
* MANUAL: will be controlled by users, after all services init, should call {@link DubboBootstrap#start()} to init app-level env
* AUTO: env will be init once {@link ServiceConfig#export()} finished
* SERVLET: will be controlled by java servlet container
*/
public enum BootstrapTakeoverMode {
SPRING,
MANUAL,
AUTO,
SERVLET
}
| 8,583 |
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/bootstrap/DubboBootstrap.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployListenerAdapter;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
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.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.config.bootstrap.builders.ApplicationBuilder;
import org.apache.dubbo.config.bootstrap.builders.ConfigCenterBuilder;
import org.apache.dubbo.config.bootstrap.builders.ConsumerBuilder;
import org.apache.dubbo.config.bootstrap.builders.MetadataReportBuilder;
import org.apache.dubbo.config.bootstrap.builders.ProtocolBuilder;
import org.apache.dubbo.config.bootstrap.builders.ProviderBuilder;
import org.apache.dubbo.config.bootstrap.builders.ReferenceBuilder;
import org.apache.dubbo.config.bootstrap.builders.RegistryBuilder;
import org.apache.dubbo.config.bootstrap.builders.ServiceBuilder;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import static java.util.Collections.singletonList;
/**
* See {@link ApplicationModel} and {@link ExtensionLoader} for why this class is designed to be singleton.
* <p>
* The bootstrap class of Dubbo
* <p>
* Get singleton instance by calling static method {@link #getInstance()}.
* Designed as singleton because some classes inside Dubbo, such as ExtensionLoader, are designed only for one instance per process.
*
* @since 2.7.5
*/
public final class DubboBootstrap {
private static final String NAME = DubboBootstrap.class.getSimpleName();
private static final Logger logger = LoggerFactory.getLogger(DubboBootstrap.class);
private static final ConcurrentMap<ApplicationModel, DubboBootstrap> instanceMap = new ConcurrentHashMap<>();
private static volatile DubboBootstrap instance;
private final AtomicBoolean awaited = new AtomicBoolean(false);
private volatile BootstrapTakeoverMode takeoverMode = BootstrapTakeoverMode.AUTO;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private final ExecutorRepository executorRepository;
private final Environment environment;
private final ApplicationModel applicationModel;
private final ConfigManager configManager;
private final ApplicationDeployer applicationDeployer;
/**
* See {@link ApplicationModel} and {@link ExtensionLoader} for why DubboBootstrap is designed to be singleton.
*/
public static DubboBootstrap getInstance() {
if (instance == null) {
synchronized (DubboBootstrap.class) {
if (instance == null) {
instance = DubboBootstrap.getInstance(ApplicationModel.defaultModel());
}
}
}
return instance;
}
public static DubboBootstrap getInstance(ApplicationModel applicationModel) {
return ConcurrentHashMapUtils.computeIfAbsent(
instanceMap, applicationModel, _k -> new DubboBootstrap(applicationModel));
}
public static DubboBootstrap newInstance() {
return getInstance(FrameworkModel.defaultModel().newApplication());
}
public static DubboBootstrap newInstance(FrameworkModel frameworkModel) {
return getInstance(frameworkModel.newApplication());
}
/**
* Try reset dubbo status for new instance.
*
* @deprecated For testing purposes only
*/
@Deprecated
public static void reset() {
reset(true);
}
/**
* Try reset dubbo status for new instance.
*
* @deprecated For testing purposes only
*/
@Deprecated
public static void reset(boolean destroy) {
if (destroy) {
if (instance != null) {
instance.destroy();
instance = null;
}
FrameworkModel.destroyAll();
} else {
instance = null;
}
ApplicationModel.reset();
}
private DubboBootstrap(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
configManager = applicationModel.getApplicationConfigManager();
environment = applicationModel.modelEnvironment();
executorRepository = ExecutorRepository.getInstance(applicationModel);
applicationDeployer = applicationModel.getDeployer();
// listen deploy events
applicationDeployer.addDeployListener(new DeployListenerAdapter<ApplicationModel>() {
@Override
public void onStarted(ApplicationModel scopeModel) {
notifyStarted(applicationModel);
}
@Override
public void onStopped(ApplicationModel scopeModel) {
notifyStopped(applicationModel);
}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {
notifyStopped(applicationModel);
}
});
// register DubboBootstrap bean
applicationModel.getBeanFactory().registerBean(this);
}
private void notifyStarted(ApplicationModel applicationModel) {
ExtensionLoader<DubboBootstrapStartStopListener> exts =
applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class);
exts.getSupportedExtensionInstances().forEach(ext -> ext.onStart(DubboBootstrap.this));
}
private void notifyStopped(ApplicationModel applicationModel) {
ExtensionLoader<DubboBootstrapStartStopListener> exts =
applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class);
exts.getSupportedExtensionInstances().forEach(ext -> ext.onStop(DubboBootstrap.this));
executeMutually(() -> {
awaited.set(true);
condition.signalAll();
});
instanceMap.remove(applicationModel);
}
/**
* Initialize
*/
public void initialize() {
applicationDeployer.initialize();
}
/**
* Start dubbo application and wait for finish
*/
public DubboBootstrap start() {
this.start(true);
return this;
}
/**
* Start dubbo application
*
* @param wait If true, wait for startup to complete, or else no waiting.
* @return
*/
public DubboBootstrap start(boolean wait) {
Future future = applicationDeployer.start();
if (wait) {
try {
future.get();
} catch (Exception e) {
throw new IllegalStateException("await dubbo application start finish failure", e);
}
}
return this;
}
/**
* Start dubbo application but no wait for finish.
*
* @return the future object
*/
public Future asyncStart() {
return applicationDeployer.start();
}
/**
* Stop dubbo application
*
* @return
* @throws IllegalStateException
*/
public DubboBootstrap stop() throws IllegalStateException {
destroy();
return this;
}
public void destroy() {
applicationModel.destroy();
}
public boolean isInitialized() {
return applicationDeployer.isInitialized();
}
public boolean isPending() {
return applicationDeployer.isPending();
}
/**
* @return true if the dubbo application is starting or has been started.
*/
public boolean isRunning() {
return applicationDeployer.isRunning();
}
/**
* @return true if the dubbo application is starting.
* @see #isStarted()
*/
public boolean isStarting() {
return applicationDeployer.isStarting();
}
/**
* @return true if the dubbo application has been started.
* @see #start()
* @see #isStarting()
*/
public boolean isStarted() {
return applicationDeployer.isStarted();
}
/**
* @return true if the dubbo application is stopping.
* @see #isStopped()
*/
public boolean isStopping() {
return applicationDeployer.isStopping();
}
/**
* @return true if the dubbo application is stopping.
* @see #isStopped()
*/
public boolean isStopped() {
return applicationDeployer.isStopped();
}
/**
* Block current thread to be await.
*
* @return {@link DubboBootstrap}
*/
public DubboBootstrap await() {
// if has been waited, no need to wait again, return immediately
if (!awaited.get()) {
if (!isStopped()) {
executeMutually(() -> {
while (!awaited.get()) {
if (logger.isInfoEnabled()) {
logger.info(NAME + " awaiting ...");
}
try {
condition.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
}
return this;
}
public ReferenceCache getCache() {
return applicationDeployer.getReferenceCache();
}
private void executeMutually(Runnable runnable) {
try {
lock.lock();
runnable.run();
} finally {
lock.unlock();
}
}
public ApplicationConfig getApplication() {
return configManager.getApplicationOrElseThrow();
}
public void setTakeoverMode(BootstrapTakeoverMode takeoverMode) {
// TODO this.started.set(false);
this.takeoverMode = takeoverMode;
}
public BootstrapTakeoverMode getTakeoverMode() {
return takeoverMode;
}
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public ConfigManager getConfigManager() {
return configManager;
}
// MetadataReportConfig correlative methods
public DubboBootstrap metadataReport(Consumer<MetadataReportBuilder> consumerBuilder) {
return metadataReport(null, consumerBuilder);
}
public DubboBootstrap metadataReport(String id, Consumer<MetadataReportBuilder> consumerBuilder) {
MetadataReportBuilder metadataReportBuilder = createMetadataReportBuilder(id);
consumerBuilder.accept(metadataReportBuilder);
return this;
}
public DubboBootstrap metadataReport(MetadataReportConfig metadataReportConfig) {
configManager.addMetadataReport(metadataReportConfig);
return this;
}
public DubboBootstrap metadataReports(List<MetadataReportConfig> metadataReportConfigs) {
if (CollectionUtils.isEmpty(metadataReportConfigs)) {
return this;
}
configManager.addMetadataReports(metadataReportConfigs);
return this;
}
// {@link ApplicationConfig} correlative methods
/**
* Set the name of application
*
* @param name the name of application
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(String name) {
return application(name, builder -> {
// DO NOTHING
});
}
/**
* Set the name of application and it's future build
*
* @param name the name of application
* @param consumerBuilder {@link ApplicationBuilder}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(String name, Consumer<ApplicationBuilder> consumerBuilder) {
ApplicationBuilder builder = createApplicationBuilder(name);
consumerBuilder.accept(builder);
return application(builder.build());
}
/**
* Set the {@link ApplicationConfig}
*
* @param applicationConfig the {@link ApplicationConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(ApplicationConfig applicationConfig) {
applicationConfig.setScopeModel(applicationModel);
configManager.setApplication(applicationConfig);
return this;
}
// {@link RegistryConfig} correlative methods
/**
* Add an instance of {@link RegistryConfig}
*
* @param consumerBuilder the {@link Consumer} of {@link RegistryBuilder}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(Consumer<RegistryBuilder> consumerBuilder) {
return registry(null, consumerBuilder);
}
/**
* Add an instance of {@link RegistryConfig} with the specified ID
*
* @param id the {@link RegistryConfig#getId() id} of {@link RegistryConfig}
* @param consumerBuilder the {@link Consumer} of {@link RegistryBuilder}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(String id, Consumer<RegistryBuilder> consumerBuilder) {
RegistryBuilder builder = createRegistryBuilder(id);
consumerBuilder.accept(builder);
return registry(builder.build());
}
/**
* Add an instance of {@link RegistryConfig}
*
* @param registryConfig an instance of {@link RegistryConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(RegistryConfig registryConfig) {
registryConfig.setScopeModel(applicationModel);
configManager.addRegistry(registryConfig);
return this;
}
/**
* Add an instance of {@link RegistryConfig}
*
* @param registryConfigs the multiple instances of {@link RegistryConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registries(List<RegistryConfig> registryConfigs) {
if (CollectionUtils.isEmpty(registryConfigs)) {
return this;
}
registryConfigs.forEach(this::registry);
return this;
}
// {@link ProtocolConfig} correlative methods
public DubboBootstrap protocol(Consumer<ProtocolBuilder> consumerBuilder) {
return protocol(null, consumerBuilder);
}
public DubboBootstrap protocol(String id, Consumer<ProtocolBuilder> consumerBuilder) {
ProtocolBuilder builder = createProtocolBuilder(id);
consumerBuilder.accept(builder);
return protocol(builder.build());
}
public DubboBootstrap protocol(ProtocolConfig protocolConfig) {
return protocols(singletonList(protocolConfig));
}
public DubboBootstrap protocols(List<ProtocolConfig> protocolConfigs) {
if (CollectionUtils.isEmpty(protocolConfigs)) {
return this;
}
for (ProtocolConfig protocolConfig : protocolConfigs) {
protocolConfig.setScopeModel(applicationModel);
configManager.addProtocol(protocolConfig);
}
return this;
}
// {@link ServiceConfig} correlative methods
public <S> DubboBootstrap service(Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(null, consumerBuilder);
}
public <S> DubboBootstrap service(String id, Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(createServiceConfig(id, consumerBuilder));
}
private <S> ServiceConfig createServiceConfig(String id, Consumer<ServiceBuilder<S>> consumerBuilder) {
ServiceBuilder builder = createServiceBuilder(id);
consumerBuilder.accept(builder);
ServiceConfig serviceConfig = builder.build();
return serviceConfig;
}
public DubboBootstrap services(List<ServiceConfig> serviceConfigs) {
if (CollectionUtils.isEmpty(serviceConfigs)) {
return this;
}
for (ServiceConfig serviceConfig : serviceConfigs) {
this.service(serviceConfig);
}
return this;
}
public DubboBootstrap service(ServiceConfig<?> serviceConfig) {
this.service(serviceConfig, applicationModel.getDefaultModule());
return this;
}
public DubboBootstrap service(ServiceConfig<?> serviceConfig, ModuleModel moduleModel) {
serviceConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addService(serviceConfig);
return this;
}
// {@link Reference} correlative methods
public <S> DubboBootstrap reference(Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(null, consumerBuilder);
}
public <S> DubboBootstrap reference(String id, Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(createReferenceConfig(id, consumerBuilder));
}
private <S> ReferenceConfig createReferenceConfig(String id, Consumer<ReferenceBuilder<S>> consumerBuilder) {
ReferenceBuilder builder = createReferenceBuilder(id);
consumerBuilder.accept(builder);
ReferenceConfig referenceConfig = builder.build();
return referenceConfig;
}
public DubboBootstrap references(List<ReferenceConfig> referenceConfigs) {
if (CollectionUtils.isEmpty(referenceConfigs)) {
return this;
}
for (ReferenceConfig referenceConfig : referenceConfigs) {
this.reference(referenceConfig);
}
return this;
}
public DubboBootstrap reference(ReferenceConfig<?> referenceConfig) {
return reference(referenceConfig, applicationModel.getDefaultModule());
}
public DubboBootstrap reference(ReferenceConfig<?> referenceConfig, ModuleModel moduleModel) {
referenceConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addReference(referenceConfig);
return this;
}
// {@link ProviderConfig} correlative methods
public DubboBootstrap provider(Consumer<ProviderBuilder> builderConsumer) {
provider(null, builderConsumer);
return this;
}
public DubboBootstrap provider(String id, Consumer<ProviderBuilder> builderConsumer) {
this.provider(createProviderConfig(id, builderConsumer));
return this;
}
private ProviderConfig createProviderConfig(String id, Consumer<ProviderBuilder> builderConsumer) {
ProviderBuilder builder = createProviderBuilder(id);
builderConsumer.accept(builder);
ProviderConfig providerConfig = builder.build();
return providerConfig;
}
public DubboBootstrap provider(ProviderConfig providerConfig) {
return this.provider(providerConfig, applicationModel.getDefaultModule());
}
public DubboBootstrap providers(List<ProviderConfig> providerConfigs) {
for (ProviderConfig providerConfig : providerConfigs) {
this.provider(providerConfig, applicationModel.getDefaultModule());
}
return this;
}
public DubboBootstrap provider(ProviderConfig providerConfig, ModuleModel moduleModel) {
providerConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addProvider(providerConfig);
return this;
}
// {@link ConsumerConfig} correlative methods
public DubboBootstrap consumer(Consumer<ConsumerBuilder> builderConsumer) {
return consumer(null, builderConsumer);
}
public DubboBootstrap consumer(String id, Consumer<ConsumerBuilder> builderConsumer) {
return consumer(createConsumerConfig(id, builderConsumer));
}
private ConsumerConfig createConsumerConfig(String id, Consumer<ConsumerBuilder> builderConsumer) {
ConsumerBuilder builder = createConsumerBuilder(id);
builderConsumer.accept(builder);
ConsumerConfig consumerConfig = builder.build();
return consumerConfig;
}
public DubboBootstrap consumer(ConsumerConfig consumerConfig) {
return this.consumer(consumerConfig, applicationModel.getDefaultModule());
}
public DubboBootstrap consumers(List<ConsumerConfig> consumerConfigs) {
for (ConsumerConfig consumerConfig : consumerConfigs) {
this.consumer(consumerConfig, applicationModel.getDefaultModule());
}
return this;
}
public DubboBootstrap consumer(ConsumerConfig consumerConfig, ModuleModel moduleModel) {
consumerConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addConsumer(consumerConfig);
return this;
}
public DubboBootstrap module(ModuleConfig moduleConfig) {
this.module(moduleConfig, applicationModel.getDefaultModule());
return this;
}
public DubboBootstrap module(ModuleConfig moduleConfig, ModuleModel moduleModel) {
moduleConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().setModule(moduleConfig);
return this;
}
// module configs end
// {@link ConfigCenterConfig} correlative methods
public DubboBootstrap configCenter(Consumer<ConfigCenterBuilder> consumerBuilder) {
return configCenter(null, consumerBuilder);
}
public DubboBootstrap configCenter(String id, Consumer<ConfigCenterBuilder> consumerBuilder) {
ConfigCenterBuilder configCenterBuilder = createConfigCenterBuilder(id);
consumerBuilder.accept(configCenterBuilder);
return this;
}
public DubboBootstrap configCenter(ConfigCenterConfig configCenterConfig) {
configCenterConfig.setScopeModel(applicationModel);
configManager.addConfigCenter(configCenterConfig);
return this;
}
public DubboBootstrap configCenters(List<ConfigCenterConfig> configCenterConfigs) {
if (CollectionUtils.isEmpty(configCenterConfigs)) {
return this;
}
for (ConfigCenterConfig configCenterConfig : configCenterConfigs) {
this.configCenter(configCenterConfig);
}
return this;
}
public DubboBootstrap monitor(MonitorConfig monitor) {
monitor.setScopeModel(applicationModel);
configManager.setMonitor(monitor);
return this;
}
public DubboBootstrap metrics(MetricsConfig metrics) {
metrics.setScopeModel(applicationModel);
configManager.setMetrics(metrics);
return this;
}
public DubboBootstrap tracing(TracingConfig tracing) {
tracing.setScopeModel(applicationModel);
configManager.setTracing(tracing);
return this;
}
public DubboBootstrap ssl(SslConfig sslConfig) {
sslConfig.setScopeModel(applicationModel);
configManager.setSsl(sslConfig);
return this;
}
/* serve for builder apis, begin */
private ApplicationBuilder createApplicationBuilder(String name) {
return new ApplicationBuilder().name(name);
}
private RegistryBuilder createRegistryBuilder(String id) {
return new RegistryBuilder().id(id);
}
private MetadataReportBuilder createMetadataReportBuilder(String id) {
return new MetadataReportBuilder().id(id);
}
private ConfigCenterBuilder createConfigCenterBuilder(String id) {
return new ConfigCenterBuilder().id(id);
}
private ProtocolBuilder createProtocolBuilder(String id) {
return new ProtocolBuilder().id(id);
}
private ServiceBuilder createServiceBuilder(String id) {
return new ServiceBuilder().id(id);
}
private ReferenceBuilder createReferenceBuilder(String id) {
return new ReferenceBuilder().id(id);
}
private ProviderBuilder createProviderBuilder(String id) {
return new ProviderBuilder().id(id);
}
private ConsumerBuilder createConsumerBuilder(String id) {
return new ConsumerBuilder().id(id);
}
/* serve for builder apis, end */
public Module newModule() {
return new Module(applicationModel.newModule());
}
public Module newModule(ModuleConfig moduleConfig) {
ModuleModel moduleModel = applicationModel.newModule();
moduleConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().setModule(moduleConfig);
return new Module(moduleModel);
}
public DubboBootstrap endModule() {
return this;
}
public class Module {
private ModuleModel moduleModel;
private DubboBootstrap bootstrap;
public Module(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
this.bootstrap = DubboBootstrap.this;
}
public DubboBootstrap endModule() {
return this.bootstrap.endModule();
}
public ModuleModel getModuleModel() {
return moduleModel;
}
public Module config(ModuleConfig moduleConfig) {
this.moduleModel.getConfigManager().setModule(moduleConfig);
return this;
}
// {@link ServiceConfig} correlative methods
public <S> Module service(Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(null, consumerBuilder);
}
public <S> Module service(String id, Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(createServiceConfig(id, consumerBuilder));
}
public Module services(List<ServiceConfig> serviceConfigs) {
if (CollectionUtils.isEmpty(serviceConfigs)) {
return this;
}
for (ServiceConfig serviceConfig : serviceConfigs) {
this.service(serviceConfig);
}
return this;
}
public Module service(ServiceConfig<?> serviceConfig) {
DubboBootstrap.this.service(serviceConfig, moduleModel);
return this;
}
// {@link Reference} correlative methods
public <S> Module reference(Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(null, consumerBuilder);
}
public <S> Module reference(String id, Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(createReferenceConfig(id, consumerBuilder));
}
public Module reference(ReferenceConfig<?> referenceConfig) {
DubboBootstrap.this.reference(referenceConfig, moduleModel);
return this;
}
public Module references(List<ReferenceConfig> referenceConfigs) {
if (CollectionUtils.isEmpty(referenceConfigs)) {
return this;
}
for (ReferenceConfig referenceConfig : referenceConfigs) {
this.reference(referenceConfig);
}
return this;
}
// {@link ProviderConfig} correlative methods
public Module provider(Consumer<ProviderBuilder> builderConsumer) {
return provider(null, builderConsumer);
}
public Module provider(String id, Consumer<ProviderBuilder> builderConsumer) {
return provider(createProviderConfig(id, builderConsumer));
}
public Module provider(ProviderConfig providerConfig) {
DubboBootstrap.this.provider(providerConfig, moduleModel);
return this;
}
public Module providers(List<ProviderConfig> providerConfigs) {
if (CollectionUtils.isEmpty(providerConfigs)) {
return this;
}
for (ProviderConfig providerConfig : providerConfigs) {
DubboBootstrap.this.provider(providerConfig, moduleModel);
}
return this;
}
// {@link ConsumerConfig} correlative methods
public Module consumer(Consumer<ConsumerBuilder> builderConsumer) {
return consumer(null, builderConsumer);
}
public Module consumer(String id, Consumer<ConsumerBuilder> builderConsumer) {
return consumer(createConsumerConfig(id, builderConsumer));
}
public Module consumer(ConsumerConfig consumerConfig) {
DubboBootstrap.this.consumer(consumerConfig, moduleModel);
return this;
}
public Module consumers(List<ConsumerConfig> consumerConfigs) {
if (CollectionUtils.isEmpty(consumerConfigs)) {
return this;
}
for (ConsumerConfig consumerConfig : consumerConfigs) {
DubboBootstrap.this.consumer(consumerConfig, moduleModel);
}
return this;
}
}
}
| 8,584 |
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/AbstractBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.AbstractConfig;
import java.util.HashMap;
import java.util.Map;
/**
* AbstractBuilder
*
* @param <C> The type of {@link AbstractConfig Config}
* @param <B> The type of {@link AbstractBuilder Builder}
* @since 2.7
*/
public abstract class AbstractBuilder<C extends AbstractConfig, B extends AbstractBuilder> {
/**
* The config id
*/
protected String id;
public B id(String id) {
this.id = id;
return getThis();
}
protected abstract B getThis();
protected static Map<String, String> appendParameter(Map<String, String> parameters, String key, String value) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put(key, value);
return parameters;
}
protected static Map<String, String> appendParameters(
Map<String, String> parameters, Map<String, String> appendParameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.putAll(appendParameters);
return parameters;
}
protected void build(C instance) {
if (!StringUtils.isEmpty(id)) {
instance.setId(id);
}
}
/**
* Build an instance of {@link AbstractConfig config}
*
* @return an instance of {@link AbstractConfig config}
*/
public abstract C build();
}
| 8,585 |
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/ArgumentBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ArgumentConfig;
/**
* This is a builder for build {@link ArgumentConfig}.
* @since 2.7
*/
public class ArgumentBuilder {
/**
* The argument index: index -1 represents not set
*/
private Integer index = -1;
/**
* Argument type
*/
private String type;
/**
* Whether the argument is the callback interface
*/
private Boolean callback;
public ArgumentBuilder index(Integer index) {
this.index = index;
return this;
}
public ArgumentBuilder type(String type) {
this.type = type;
return this;
}
public ArgumentBuilder callback(Boolean callback) {
this.callback = callback;
return this;
}
public ArgumentConfig build() {
ArgumentConfig argumentConfig = new ArgumentConfig();
argumentConfig.setIndex(index);
argumentConfig.setType(type);
argumentConfig.setCallback(callback);
return argumentConfig;
}
}
| 8,586 |
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/MetadataReportBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.MetadataReportConfig;
import java.util.Map;
/**
* This is a builder for build {@link MetadataReportConfig}.
*
* @since 2.7
*/
public class MetadataReportBuilder extends AbstractBuilder<MetadataReportConfig, MetadataReportBuilder> {
/**
* Register center address
*/
private String address;
/**
* Username to login register center
*/
private String username;
/**
* Password to login register center
*/
private String password;
/**
* Request timeout in milliseconds for register center
*/
private Integer timeout;
/**
* The group the metadata in . It is the same as registry
*/
private String group;
/**
* Customized parameters
*/
private Map<String, String> parameters;
private Integer retryTimes;
private Integer retryPeriod;
/**
* By default the metadata store will store full metadata repeatedly every day .
*/
private Boolean cycleReport;
/**
* Sync report, default async
*/
private Boolean syncReport;
/**
* Decide the behaviour when initial connection try fails,
* 'true' means interrupt the whole process once fail.
* The default value is true
*/
private Boolean check;
public static MetadataReportBuilder newBuilder() {
return new MetadataReportBuilder();
}
public MetadataReportBuilder address(String address) {
this.address = address;
return getThis();
}
public MetadataReportBuilder username(String username) {
this.username = username;
return getThis();
}
public MetadataReportBuilder password(String password) {
this.password = password;
return getThis();
}
public MetadataReportBuilder timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
}
public MetadataReportBuilder group(String group) {
this.group = group;
return getThis();
}
public MetadataReportBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(this.parameters, appendParameters);
return getThis();
}
public MetadataReportBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(this.parameters, key, value);
return getThis();
}
public MetadataReportBuilder retryTimes(Integer retryTimes) {
this.retryTimes = retryTimes;
return getThis();
}
public MetadataReportBuilder retryPeriod(Integer retryPeriod) {
this.retryPeriod = retryPeriod;
return getThis();
}
public MetadataReportBuilder cycleReport(Boolean cycleReport) {
this.cycleReport = cycleReport;
return getThis();
}
public MetadataReportBuilder syncReport(Boolean syncReport) {
this.syncReport = syncReport;
return getThis();
}
public MetadataReportBuilder check(Boolean check) {
this.check = check;
return getThis();
}
@Override
public MetadataReportConfig build() {
MetadataReportConfig metadataReport = new MetadataReportConfig();
super.build(metadataReport);
metadataReport.setAddress(address);
metadataReport.setUsername(username);
metadataReport.setPassword(password);
metadataReport.setTimeout(timeout);
metadataReport.setGroup(group);
metadataReport.setParameters(parameters);
metadataReport.setRetryTimes(retryTimes);
metadataReport.setRetryPeriod(retryPeriod);
metadataReport.setCycleReport(cycleReport);
metadataReport.setSyncReport(syncReport);
metadataReport.setCheck(check);
return metadataReport;
}
@Override
protected MetadataReportBuilder getThis() {
return this;
}
}
| 8,587 |
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/ServiceBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.MethodConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import java.util.ArrayList;
import java.util.List;
/**
* This is a builder for build {@link ServiceConfigBase}.
*
* @since 2.7
*/
public class ServiceBuilder<U> extends AbstractServiceBuilder<ServiceConfig<U>, ServiceBuilder<U>> {
/**
* The interface name of the exported service
*/
private String interfaceName;
/**
* The interface class of the exported service
*/
private Class<?> interfaceClass;
/**
* The reference of the interface implementation
*/
private U ref;
/**
* The service name
*/
private String path;
/**
* The method configuration
*/
private List<MethodConfig> methods;
/**
* The provider configuration
*/
private ProviderConfig provider;
/**
* The providerIds
*/
private String providerIds;
/**
* whether it is a GenericService
*/
private String generic;
public static <T> ServiceBuilder<T> newBuilder() {
return new ServiceBuilder<>();
}
public ServiceBuilder<U> id(String id) {
return super.id(id);
}
public ServiceBuilder<U> interfaceName(String interfaceName) {
this.interfaceName = interfaceName;
return getThis();
}
public ServiceBuilder<U> interfaceClass(Class<?> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public ServiceBuilder<U> ref(U ref) {
this.ref = ref;
return getThis();
}
public ServiceBuilder<U> path(String path) {
this.path = path;
return getThis();
}
public ServiceBuilder<U> addMethod(MethodConfig method) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.add(method);
return getThis();
}
public ServiceBuilder<U> addMethods(List<? extends MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
}
public ServiceBuilder<U> provider(ProviderConfig provider) {
this.provider = provider;
return getThis();
}
public ServiceBuilder<U> providerIds(String providerIds) {
this.providerIds = providerIds;
return getThis();
}
public ServiceBuilder<U> generic(String generic) {
this.generic = generic;
return getThis();
}
// @Override
// public ServiceBuilder<U> mock(String mock) {
// throw new IllegalArgumentException("mock doesn't support on provider side");
// }
// @Override
// public ServiceBuilder<U> mock(Boolean mock) {
// throw new IllegalArgumentException("mock doesn't support on provider side");
// }
public ServiceConfig<U> build() {
ServiceConfig<U> serviceConfig = new ServiceConfig<>();
super.build(serviceConfig);
serviceConfig.setInterface(interfaceName);
serviceConfig.setInterface(interfaceClass);
serviceConfig.setRef(ref);
serviceConfig.setPath(path);
serviceConfig.setMethods(methods);
serviceConfig.setProvider(provider);
serviceConfig.setProviderIds(providerIds);
serviceConfig.setGeneric(generic);
return serviceConfig;
}
@Override
protected ServiceBuilder<U> getThis() {
return this;
}
}
| 8,588 |
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/MethodBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ArgumentConfig;
import org.apache.dubbo.config.MethodConfig;
import java.util.ArrayList;
import java.util.List;
/**
* This is a builder for build {@link MethodConfig}.
*
* @since 2.7
*/
public class MethodBuilder extends AbstractMethodBuilder<MethodConfig, MethodBuilder> {
/**
* The method name
*/
private String name;
/**
* Stat
*/
private Integer stat;
/**
* Whether to retry
*/
private Boolean retry;
/**
* If it's reliable
*/
private Boolean reliable;
/**
* Thread limits for method invocations
*/
private Integer executes;
/**
* If it's deprecated
*/
private Boolean deprecated;
/**
* Whether to enable sticky
*/
private Boolean sticky;
/**
* Whether need to return
*/
private Boolean isReturn;
/**
* Callback instance when async-call is invoked
*/
private Object oninvoke;
/**
* Callback method when async-call is invoked
*/
private String oninvokeMethod;
/**
* Callback instance when async-call is returned
*/
private Object onreturn;
/**
* Callback method when async-call is returned
*/
private String onreturnMethod;
/**
* Callback instance when async-call has exception thrown
*/
private Object onthrow;
/**
* Callback method when async-call has exception thrown
*/
private String onthrowMethod;
/**
* The method arguments
*/
private List<ArgumentConfig> arguments;
/**
* These properties come from MethodConfig's parent Config module, they will neither be collected directly from xml or API nor be delivered to url
*/
private String service;
private String serviceId;
public MethodBuilder name(String name) {
this.name = name;
return getThis();
}
public MethodBuilder stat(Integer stat) {
this.stat = stat;
return getThis();
}
public MethodBuilder retry(Boolean retry) {
this.retry = retry;
return getThis();
}
public MethodBuilder reliable(Boolean reliable) {
this.reliable = reliable;
return getThis();
}
public MethodBuilder executes(Integer executes) {
this.executes = executes;
return getThis();
}
public MethodBuilder deprecated(Boolean deprecated) {
this.deprecated = deprecated;
return getThis();
}
public MethodBuilder sticky(Boolean sticky) {
this.sticky = sticky;
return getThis();
}
public MethodBuilder isReturn(Boolean isReturn) {
this.isReturn = isReturn;
return getThis();
}
public MethodBuilder oninvoke(Object oninvoke) {
this.oninvoke = oninvoke;
return getThis();
}
public MethodBuilder oninvokeMethod(String oninvokeMethod) {
this.oninvokeMethod = oninvokeMethod;
return getThis();
}
public MethodBuilder onreturn(Object onreturn) {
this.onreturn = onreturn;
return getThis();
}
public MethodBuilder onreturnMethod(String onreturnMethod) {
this.onreturnMethod = onreturnMethod;
return getThis();
}
public MethodBuilder onthrow(Object onthrow) {
this.onthrow = onthrow;
return getThis();
}
public MethodBuilder onthrowMethod(String onthrowMethod) {
this.onthrowMethod = onthrowMethod;
return getThis();
}
public MethodBuilder addArguments(List<? extends ArgumentConfig> arguments) {
if (this.arguments == null) {
this.arguments = new ArrayList<>();
}
this.arguments.addAll(arguments);
return getThis();
}
public MethodBuilder addArgument(ArgumentConfig argument) {
if (this.arguments == null) {
this.arguments = new ArrayList<>();
}
this.arguments.add(argument);
return getThis();
}
public MethodBuilder service(String service) {
this.service = service;
return getThis();
}
public MethodBuilder serviceId(String serviceId) {
this.serviceId = serviceId;
return getThis();
}
public MethodConfig build() {
MethodConfig methodConfig = new MethodConfig();
super.build(methodConfig);
methodConfig.setArguments(arguments);
methodConfig.setDeprecated(deprecated);
methodConfig.setExecutes(executes);
methodConfig.setName(name);
methodConfig.setOninvoke(oninvoke);
methodConfig.setOninvokeMethod(oninvokeMethod);
methodConfig.setOnreturn(onreturn);
methodConfig.setOnreturnMethod(onreturnMethod);
methodConfig.setOnthrow(onthrow);
methodConfig.setOnthrowMethod(onthrowMethod);
methodConfig.setReturn(isReturn);
methodConfig.setService(service);
methodConfig.setServiceId(serviceId);
methodConfig.setSticky(sticky);
methodConfig.setReliable(reliable);
methodConfig.setStat(stat);
methodConfig.setRetry(retry);
return methodConfig;
}
@Override
protected MethodBuilder getThis() {
return this;
}
}
| 8,589 |
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/ApplicationBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ApplicationConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.config.Constants.PRODUCTION_ENVIRONMENT;
/**
* This is a builder for build {@link ApplicationConfig}.
* @since 2.7
*/
public class ApplicationBuilder extends AbstractBuilder<ApplicationConfig, ApplicationBuilder> {
private String name;
private String metadata;
private String version;
private String owner;
private String organization;
private String architecture;
private String environment = PRODUCTION_ENVIRONMENT;
private String compiler;
private String logger;
private List<RegistryConfig> registries;
private String registryIds;
private MonitorConfig monitor;
private Boolean isDefault;
private String dumpDirectory;
private Boolean qosEnable;
private Integer qosPort;
private Boolean qosAcceptForeignIp;
private Map<String, String> parameters;
private String shutwait;
private Integer metadataServicePort;
private String livenessProbe;
private String readinessProbe;
private String startupProbe;
public static ApplicationBuilder newBuilder() {
return new ApplicationBuilder();
}
public ApplicationBuilder name(String name) {
this.name = name;
return getThis();
}
public ApplicationBuilder metadata(String metadata) {
this.metadata = metadata;
return getThis();
}
public ApplicationBuilder version(String version) {
this.version = version;
return getThis();
}
public ApplicationBuilder owner(String owner) {
this.owner = owner;
return getThis();
}
public ApplicationBuilder organization(String organization) {
this.organization = organization;
return getThis();
}
public ApplicationBuilder architecture(String architecture) {
this.architecture = architecture;
return getThis();
}
public ApplicationBuilder environment(String environment) {
this.environment = environment;
return getThis();
}
public ApplicationBuilder compiler(String compiler) {
this.compiler = compiler;
return getThis();
}
public ApplicationBuilder logger(String logger) {
this.logger = logger;
return getThis();
}
public ApplicationBuilder addRegistry(RegistryConfig registry) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.add(registry);
return getThis();
}
public ApplicationBuilder addRegistries(List<? extends RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
}
public ApplicationBuilder registryIds(String registryIds) {
this.registryIds = registryIds;
return getThis();
}
public ApplicationBuilder monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
}
public ApplicationBuilder monitor(String monitor) {
this.monitor = new MonitorConfig(monitor);
return getThis();
}
public ApplicationBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ApplicationBuilder dumpDirectory(String dumpDirectory) {
this.dumpDirectory = dumpDirectory;
return getThis();
}
public ApplicationBuilder qosEnable(Boolean qosEnable) {
this.qosEnable = qosEnable;
return getThis();
}
public ApplicationBuilder qosPort(Integer qosPort) {
this.qosPort = qosPort;
return getThis();
}
public ApplicationBuilder qosAcceptForeignIp(Boolean qosAcceptForeignIp) {
this.qosAcceptForeignIp = qosAcceptForeignIp;
return getThis();
}
public ApplicationBuilder shutwait(String shutwait) {
this.shutwait = shutwait;
return getThis();
}
public ApplicationBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public ApplicationBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public ApplicationBuilder metadataServicePort(Integer metadataServicePort) {
this.metadataServicePort = metadataServicePort;
return getThis();
}
public ApplicationBuilder livenessProbe(String livenessProbe) {
this.livenessProbe = livenessProbe;
return getThis();
}
public ApplicationBuilder readinessProbe(String readinessProbe) {
this.readinessProbe = readinessProbe;
return getThis();
}
public ApplicationBuilder startupProbe(String startupProbe) {
this.startupProbe = startupProbe;
return getThis();
}
public ApplicationConfig build() {
ApplicationConfig config = new ApplicationConfig();
super.build(config);
config.setName(name);
config.setMetadataType(metadata);
config.setVersion(this.version);
config.setOwner(this.owner);
config.setOrganization(this.organization);
config.setArchitecture(this.architecture);
config.setEnvironment(this.environment);
config.setCompiler(this.compiler);
config.setLogger(this.logger);
config.setRegistries(this.registries);
config.setRegistryIds(this.registryIds);
config.setMonitor(this.monitor);
config.setDefault(this.isDefault);
config.setDumpDirectory(this.dumpDirectory);
config.setQosEnable(this.qosEnable);
config.setQosPort(this.qosPort);
config.setQosAcceptForeignIp(this.qosAcceptForeignIp);
config.setMetadataServicePort(this.metadataServicePort);
config.setLivenessProbe(this.livenessProbe);
config.setReadinessProbe(this.readinessProbe);
config.setStartupProbe(this.startupProbe);
config.setParameters(this.parameters);
if (!StringUtils.isEmpty(shutwait)) {
config.setShutwait(shutwait);
}
return config;
}
@Override
protected ApplicationBuilder getThis() {
return this;
}
}
| 8,590 |
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/AbstractInterfaceBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.AbstractInterfaceConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.Filter;
import java.util.ArrayList;
import java.util.List;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractInterfaceBuilder<
T extends AbstractInterfaceConfig, B extends AbstractInterfaceBuilder<T, B>>
extends AbstractMethodBuilder<T, B> {
/**
* Local impl class name for the service interface
*/
protected String local;
/**
* Local stub class name for the service interface
*/
protected String stub;
/**
* Service monitor
*/
protected MonitorConfig monitor;
/**
* Strategies for generating dynamic agents,there are two strategies can be choosed: jdk and javassist
*/
protected String proxy;
/**
* Cluster type
*/
protected String cluster;
/**
* The {@link Filter} when the provider side exposed a service or the customer side references a remote service used,
* if there are more than one, you can use commas to separate them
*/
protected String filter;
/**
* The Listener when the provider side exposes a service or the customer side references a remote service used
* if there are more than one, you can use commas to separate them
*/
protected String listener;
/**
* The owner of the service providers
*/
protected String owner;
/**
* Connection limits, 0 means shared connection, otherwise it defines the connections delegated to the current service
*/
protected Integer connections;
/**
* The layer of service providers
*/
protected String layer;
/**
* The application info
*/
protected ApplicationConfig application;
/**
* The module info
*/
protected ModuleConfig module;
/**
* Registry centers
*/
protected List<RegistryConfig> registries;
protected String registryIds;
// connection events
protected String onconnect;
/**
* Disconnection events
*/
protected String ondisconnect;
protected MetadataReportConfig metadataReportConfig;
protected ConfigCenterConfig configCenter;
// callback limits
private Integer callbacks;
// the scope for referring/exporting a service, if it's local, it means searching in current JVM only.
private String scope;
private String tag;
/**
* @param local
* @see AbstractInterfaceBuilder#stub(String)
* @deprecated Replace to <code>stub(String)</code>
*/
@Deprecated
public B local(String local) {
this.local = local;
return getThis();
}
/**
* @param local
* @see AbstractInterfaceBuilder#stub(Boolean)
* @deprecated Replace to <code>stub(Boolean)</code>
*/
@Deprecated
public B local(Boolean local) {
if (local != null) {
this.local = local.toString();
} else {
this.local = null;
}
return getThis();
}
public B stub(String stub) {
this.stub = stub;
return getThis();
}
public B stub(Boolean stub) {
if (stub != null) {
this.stub = stub.toString();
} else {
this.stub = null;
}
return getThis();
}
public B monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
}
public B monitor(String monitor) {
this.monitor = new MonitorConfig(monitor);
return getThis();
}
public B proxy(String proxy) {
this.proxy = proxy;
return getThis();
}
public B cluster(String cluster) {
this.cluster = cluster;
return getThis();
}
public B filter(String filter) {
this.filter = filter;
return getThis();
}
public B listener(String listener) {
this.listener = listener;
return getThis();
}
public B owner(String owner) {
this.owner = owner;
return getThis();
}
public B connections(Integer connections) {
this.connections = connections;
return getThis();
}
public B layer(String layer) {
this.layer = layer;
return getThis();
}
public B application(ApplicationConfig application) {
this.application = application;
return getThis();
}
public B module(ModuleConfig module) {
this.module = module;
return getThis();
}
public B addRegistries(List<RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
}
public B addRegistry(RegistryConfig registry) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.add(registry);
return getThis();
}
public B registryIds(String registryIds) {
this.registryIds = registryIds;
return getThis();
}
public B onconnect(String onconnect) {
this.onconnect = onconnect;
return getThis();
}
public B ondisconnect(String ondisconnect) {
this.ondisconnect = ondisconnect;
return getThis();
}
public B metadataReportConfig(MetadataReportConfig metadataReportConfig) {
this.metadataReportConfig = metadataReportConfig;
return getThis();
}
public B configCenter(ConfigCenterConfig configCenter) {
this.configCenter = configCenter;
return getThis();
}
public B callbacks(Integer callbacks) {
this.callbacks = callbacks;
return getThis();
}
public B scope(String scope) {
this.scope = scope;
return getThis();
}
public B tag(String tag) {
this.tag = tag;
return getThis();
}
@Override
public void build(T instance) {
super.build(instance);
if (!StringUtils.isEmpty(local)) {
instance.setLocal(local);
}
if (!StringUtils.isEmpty(stub)) {
instance.setStub(stub);
}
if (monitor != null) {
instance.setMonitor(monitor);
}
if (!StringUtils.isEmpty(proxy)) {
instance.setProxy(proxy);
}
if (!StringUtils.isEmpty(cluster)) {
instance.setCluster(cluster);
}
if (!StringUtils.isEmpty(filter)) {
instance.setFilter(filter);
}
if (!StringUtils.isEmpty(listener)) {
instance.setListener(listener);
}
if (!StringUtils.isEmpty(owner)) {
instance.setOwner(owner);
}
if (connections != null) {
instance.setConnections(connections);
}
if (!StringUtils.isEmpty(layer)) {
instance.setLayer(layer);
}
if (application != null) {
instance.setApplication(application);
}
if (module != null) {
instance.setModule(module);
}
if (registries != null) {
instance.setRegistries(registries);
}
if (!StringUtils.isEmpty(registryIds)) {
instance.setRegistryIds(registryIds);
}
if (!StringUtils.isEmpty(onconnect)) {
instance.setOnconnect(onconnect);
}
if (!StringUtils.isEmpty(ondisconnect)) {
instance.setOndisconnect(ondisconnect);
}
if (metadataReportConfig != null) {
instance.setMetadataReportConfig(metadataReportConfig);
}
if (configCenter != null) {
instance.setConfigCenter(configCenter);
}
if (callbacks != null) {
instance.setCallbacks(callbacks);
}
if (!StringUtils.isEmpty(scope)) {
instance.setScope(scope);
}
if (StringUtils.isNotEmpty(tag)) {
instance.setTag(tag);
}
}
}
| 8,591 |
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/AbstractReferenceBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.AbstractReferenceConfig;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractReferenceBuilder<
T extends AbstractReferenceConfig, B extends AbstractReferenceBuilder<T, B>>
extends AbstractInterfaceBuilder<T, B> {
/**
* Check if service provider exists, if not exists, it will be fast fail
*/
protected Boolean check;
/**
* Whether to eagle-init
*/
protected Boolean init;
/**
* Whether to use generic interface
*/
protected String generic;
/**
* Whether to find reference's instance from the current JVM
*/
protected Boolean injvm;
/**
* Lazy create connection
*/
protected Boolean lazy;
protected String reconnect;
protected Boolean sticky;
/**
* The remote service version the customer side will reference
*/
protected String version;
/**
* The remote service group the customer side will reference
*/
protected String group;
public B check(Boolean check) {
this.check = check;
return getThis();
}
public B init(Boolean init) {
this.init = init;
return getThis();
}
public B generic(String generic) {
this.generic = generic;
return getThis();
}
public B generic(Boolean generic) {
if (generic != null) {
this.generic = generic.toString();
} else {
this.generic = null;
}
return getThis();
}
/**
* @param injvm
* @see AbstractInterfaceBuilder#scope(String)
* @deprecated instead, use the parameter <b>scope</b> to judge if it's in jvm, scope=local
*/
@Deprecated
public B injvm(Boolean injvm) {
this.injvm = injvm;
return getThis();
}
public B lazy(Boolean lazy) {
this.lazy = lazy;
return getThis();
}
public B reconnect(String reconnect) {
this.reconnect = reconnect;
return getThis();
}
public B sticky(Boolean sticky) {
this.sticky = sticky;
return getThis();
}
public B version(String version) {
this.version = version;
return getThis();
}
public B group(String group) {
this.group = group;
return getThis();
}
@Override
public void build(T instance) {
super.build(instance);
if (check != null) {
instance.setCheck(check);
}
if (init != null) {
instance.setInit(init);
}
if (!StringUtils.isEmpty(generic)) {
instance.setGeneric(generic);
}
if (injvm != null) {
instance.setInjvm(injvm);
}
if (lazy != null) {
instance.setLazy(lazy);
}
if (!StringUtils.isEmpty(reconnect)) {
instance.setReconnect(reconnect);
}
if (sticky != null) {
instance.setSticky(sticky);
}
if (!StringUtils.isEmpty(version)) {
instance.setVersion(version);
}
if (!StringUtils.isEmpty(group)) {
instance.setGroup(group);
}
}
}
| 8,592 |
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/ReferenceBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import java.util.ArrayList;
import java.util.List;
import static org.apache.dubbo.common.utils.StringUtils.toCommaDelimitedString;
/**
* This is a builder for build {@link ReferenceConfigBase}.
*
* @since 2.7
*/
public class ReferenceBuilder<T> extends AbstractReferenceBuilder<ReferenceConfig<T>, ReferenceBuilder<T>> {
/**
* The interface name of the reference service
*/
private String interfaceName;
/**
* The interface class of the reference service
*/
private Class<?> interfaceClass;
/**
* client type
*/
private String client;
/**
* The url for peer-to-peer invocation
*/
private String url;
/**
* The method configs
*/
private List<MethodConfig> methods;
/**
* The consumer config (default)
*/
private ConsumerConfig consumer;
/**
* Only the service provider of the specified protocol is invoked, and other protocols are ignored.
*/
private String protocol;
/**
* The string presenting the service names that the Dubbo interface subscribed
*
* @since 2.7.8
*/
private String services;
public static <T> ReferenceBuilder<T> newBuilder() {
return new ReferenceBuilder<>();
}
public ReferenceBuilder<T> id(String id) {
return super.id(id);
}
public ReferenceBuilder<T> interfaceName(String interfaceName) {
this.interfaceName = interfaceName;
return getThis();
}
public ReferenceBuilder<T> interfaceClass(Class<?> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public ReferenceBuilder<T> client(String client) {
this.client = client;
return getThis();
}
public ReferenceBuilder<T> url(String url) {
this.url = url;
return getThis();
}
public ReferenceBuilder<T> addMethods(List<MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
}
public ReferenceBuilder<T> addMethod(MethodConfig method) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.add(method);
return getThis();
}
public ReferenceBuilder<T> consumer(ConsumerConfig consumer) {
this.consumer = consumer;
return getThis();
}
public ReferenceBuilder<T> protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
/**
* @param service one service name
* @param otherServices other service names
* @return {@link ReferenceBuilder}
* @since 2.7.8
*/
public ReferenceBuilder<T> services(String service, String... otherServices) {
this.services = toCommaDelimitedString(service, otherServices);
return getThis();
}
public ReferenceConfig<T> build() {
ReferenceConfig<T> reference = new ReferenceConfig<>();
super.build(reference);
reference.setInterface(interfaceName);
if (interfaceClass != null) {
reference.setInterface(interfaceClass);
}
reference.setClient(client);
reference.setUrl(url);
reference.setMethods(methods);
reference.setConsumer(consumer);
reference.setProtocol(protocol);
// @since 2.7.8
reference.setServices(services);
return reference;
}
@Override
protected ReferenceBuilder<T> getThis() {
return this;
}
}
| 8,593 |
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/ConsumerBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ConsumerConfig;
/**
* This is a builder for build {@link ConsumerConfig}.
*
* @since 2.7
*/
public class ConsumerBuilder extends AbstractReferenceBuilder<ConsumerConfig, ConsumerBuilder> {
/**
* Whether to use the default protocol
*/
private Boolean isDefault;
/**
* Networking framework client uses: netty, mina, etc.
*/
private String client;
/**
* Consumer thread pool type: cached, fixed, limit, eager
*/
private String threadpool;
/**
* Consumer threadpool core thread size
*/
private Integer corethreads;
/**
* Consumer threadpool thread size
*/
private Integer threads;
/**
* Consumer threadpool queue size
*/
private Integer queues;
/**
* By default, a TCP long-connection communication is shared between the consumer process and the provider process.
* This property can be set to share multiple TCP long-connection communications. Note that only the dubbo protocol takes effect.
*/
private Integer shareconnections;
/**
* Url Merge Processor
* Used to customize the URL merge of consumer and provider
*/
private String urlMergeProcessor;
public ConsumerBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ConsumerBuilder client(String client) {
this.client = client;
return getThis();
}
public ConsumerBuilder threadPool(String threadPool) {
this.threadpool = threadPool;
return getThis();
}
public ConsumerBuilder coreThreads(Integer coreThreads) {
this.corethreads = coreThreads;
return getThis();
}
public ConsumerBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ConsumerBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ConsumerBuilder shareConnections(Integer shareConnections) {
this.shareconnections = shareConnections;
return getThis();
}
public ConsumerBuilder urlMergeProcessor(String urlMergeProcessor) {
this.urlMergeProcessor = urlMergeProcessor;
return getThis();
}
@Override
public ConsumerConfig build() {
ConsumerConfig consumer = new ConsumerConfig();
super.build(consumer);
consumer.setDefault(isDefault);
consumer.setClient(client);
consumer.setThreadpool(threadpool);
consumer.setCorethreads(corethreads);
consumer.setThreads(threads);
consumer.setQueues(queues);
consumer.setShareconnections(shareconnections);
consumer.setUrlMergeProcessor(urlMergeProcessor);
return consumer;
}
@Override
protected ConsumerBuilder getThis() {
return this;
}
}
| 8,594 |
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/AbstractServiceBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.AbstractServiceConfig;
import org.apache.dubbo.config.ProtocolConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractServiceBuilder<T extends AbstractServiceConfig, B extends AbstractServiceBuilder<T, B>>
extends AbstractInterfaceBuilder<T, B> {
/**
* The service version
*/
protected String version;
/**
* The service group
*/
protected String group;
/**
* whether the service is deprecated
*/
protected Boolean deprecated;
/**
* The time delay register service (milliseconds)
*/
protected Integer delay;
/**
* Whether to export the service
*/
protected Boolean export;
/**
* The service weight
*/
protected Integer weight;
/**
* Document center
*/
protected String document;
/**
* Whether to register as a dynamic service or not on register center, it the value is false, the status will be disabled
* after the service registered,and it needs to be enabled manually; if you want to disable the service, you also need
* manual processing
*/
protected Boolean dynamic;
/**
* Whether to use token
*/
protected String token;
/**
* Whether to export access logs to logs
*/
protected String accesslog;
/**
* The protocol list the service will export with
*/
protected List<ProtocolConfig> protocols;
protected String protocolIds;
// max allowed execute times
private Integer executes;
/**
* Whether to register
*/
private Boolean register;
/**
* Warm up period
*/
private Integer warmup;
/**
* The serialization type
*/
private String serialization;
/**
* used for thread pool isolation between services
*/
private Executor executor;
/**
* The prefer serialization type
*/
private String preferSerialization;
public B version(String version) {
this.version = version;
return getThis();
}
public B group(String group) {
this.group = group;
return getThis();
}
public B deprecated(Boolean deprecated) {
this.deprecated = deprecated;
return getThis();
}
public B delay(Integer delay) {
this.delay = delay;
return getThis();
}
public B export(Boolean export) {
this.export = export;
return getThis();
}
public B weight(Integer weight) {
this.weight = weight;
return getThis();
}
public B document(String document) {
this.document = document;
return getThis();
}
public B dynamic(Boolean dynamic) {
this.dynamic = dynamic;
return getThis();
}
public B token(String token) {
this.token = token;
return getThis();
}
public B token(Boolean token) {
if (token != null) {
this.token = token.toString();
} else {
this.token = null;
}
return getThis();
}
public B accesslog(String accesslog) {
this.accesslog = accesslog;
return getThis();
}
public B accesslog(Boolean accesslog) {
if (accesslog != null) {
this.accesslog = accesslog.toString();
} else {
this.accesslog = null;
}
return getThis();
}
public B addProtocols(List<ProtocolConfig> protocols) {
if (this.protocols == null) {
this.protocols = new ArrayList<>();
}
this.protocols.addAll(protocols);
return getThis();
}
public B addProtocol(ProtocolConfig protocol) {
if (this.protocols == null) {
this.protocols = new ArrayList<>();
}
this.protocols.add(protocol);
return getThis();
}
public B protocolIds(String protocolIds) {
this.protocolIds = protocolIds;
return getThis();
}
public B executes(Integer executes) {
this.executes = executes;
return getThis();
}
public B register(Boolean register) {
this.register = register;
return getThis();
}
public B warmup(Integer warmup) {
this.warmup = warmup;
return getThis();
}
public B serialization(String serialization) {
this.serialization = serialization;
return getThis();
}
public B executor(Executor executor) {
this.executor = executor;
return getThis();
}
/**
* The prefer serialization type
*
* @param preferSerialization prefer serialization type
* @return {@link B}
*/
public B preferSerialization(String preferSerialization) {
this.preferSerialization = preferSerialization;
return getThis();
}
@Override
public void build(T instance) {
super.build(instance);
if (!StringUtils.isEmpty(version)) {
instance.setVersion(version);
}
if (!StringUtils.isEmpty(group)) {
instance.setGroup(group);
}
if (deprecated != null) {
instance.setDeprecated(deprecated);
}
if (delay != null) {
instance.setDelay(delay);
}
if (export != null) {
instance.setExport(export);
}
if (weight != null) {
instance.setWeight(weight);
}
if (!StringUtils.isEmpty(document)) {
instance.setDocument(document);
}
if (dynamic != null) {
instance.setDynamic(dynamic);
}
if (!StringUtils.isEmpty(token)) {
instance.setToken(token);
}
if (!StringUtils.isEmpty(accesslog)) {
instance.setAccesslog(accesslog);
}
if (protocols != null) {
instance.setProtocols(protocols);
}
if (!StringUtils.isEmpty(protocolIds)) {
instance.setProtocolIds(protocolIds);
}
if (executes != null) {
instance.setExecutes(executes);
}
if (register != null) {
instance.setRegister(register);
}
if (warmup != null) {
instance.setWarmup(warmup);
}
if (!StringUtils.isEmpty(serialization)) {
instance.setSerialization(serialization);
}
if (executor != null) {
instance.setExecutor(executor);
}
if (StringUtils.isNotBlank(preferSerialization)) {
instance.setPreferSerialization(preferSerialization);
}
}
}
| 8,595 |
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/InternalServiceConfigBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
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.ConsumerConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
public class InternalServiceConfigBuilder<T> {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private static final Set<String> UNACCEPTABLE_PROTOCOL =
Stream.of("rest", "grpc").collect(Collectors.toSet());
private final ApplicationModel applicationModel;
private String protocol;
private Integer port;
private String registryId;
private Class<T> interfaceClass;
private Executor executor;
private T ref;
private InternalServiceConfigBuilder(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public static <T> InternalServiceConfigBuilder<T> newBuilder(ApplicationModel applicationModel) {
return new InternalServiceConfigBuilder<>(applicationModel);
}
public InternalServiceConfigBuilder<T> interfaceClass(Class<T> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public InternalServiceConfigBuilder<T> executor(Executor executor) {
this.executor = executor;
return getThis();
}
public InternalServiceConfigBuilder<T> ref(T ref) {
this.ref = ref;
return getThis();
}
public InternalServiceConfigBuilder<T> registryId(String registryId) {
this.registryId = registryId;
return getThis();
}
public InternalServiceConfigBuilder<T> protocol(String protocol, String key) {
if (StringUtils.isEmpty(protocol) && StringUtils.isNotBlank(key)) {
Map<String, String> params = getApplicationConfig().getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
protocol = params.get(key);
}
}
this.protocol = StringUtils.isNotEmpty(protocol) ? protocol : getRelatedOrDefaultProtocol();
return getThis();
}
/**
* Get other configured protocol from environment in priority order. If get nothing, use default dubbo.
*
* @return
*/
private String getRelatedOrDefaultProtocol() {
String protocol = "";
// <dubbo:consumer/>
List<ModuleModel> moduleModels = applicationModel.getPubModuleModels();
protocol = moduleModels.stream()
.map(ModuleModel::getConfigManager)
.map(ModuleConfigManager::getConsumers)
.filter(CollectionUtils::isNotEmpty)
.flatMap(Collection::stream)
.map(ConsumerConfig::getProtocol)
.filter(StringUtils::isNotEmpty)
.filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p))
.findFirst()
.orElse("");
// <dubbo:provider/>
if (StringUtils.isEmpty(protocol)) {
Stream<ProviderConfig> providerConfigStream = moduleModels.stream()
.map(ModuleModel::getConfigManager)
.map(ModuleConfigManager::getProviders)
.filter(CollectionUtils::isNotEmpty)
.flatMap(Collection::stream);
protocol = providerConfigStream
.filter((providerConfig) -> providerConfig.getProtocol() != null
|| CollectionUtils.isNotEmpty(providerConfig.getProtocols()))
.map(providerConfig -> {
if (providerConfig.getProtocol() != null
&& StringUtils.isNotEmpty(
providerConfig.getProtocol().getName())) {
return providerConfig.getProtocol().getName();
} else {
return providerConfig.getProtocols().stream()
.map(ProtocolConfig::getName)
.filter(StringUtils::isNotEmpty)
.findFirst()
.orElse("");
}
})
.filter(StringUtils::isNotEmpty)
.filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p))
.findFirst()
.orElse("");
}
// <dubbo:protocol/>
if (StringUtils.isEmpty(protocol)) {
Collection<ProtocolConfig> protocols =
applicationModel.getApplicationConfigManager().getProtocols();
if (CollectionUtils.isNotEmpty(protocols)) {
protocol = protocols.stream()
.map(ProtocolConfig::getName)
.filter(StringUtils::isNotEmpty)
.filter(p -> !UNACCEPTABLE_PROTOCOL.contains(p))
.findFirst()
.orElse("");
}
}
// <dubbo:application/>
if (StringUtils.isEmpty(protocol)) {
protocol = getApplicationConfig().getProtocol();
if (StringUtils.isEmpty(protocol)) {
Map<String, String> params = getApplicationConfig().getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
protocol = params.get(APPLICATION_PROTOCOL_KEY);
}
}
}
return StringUtils.isNotEmpty(protocol) && !UNACCEPTABLE_PROTOCOL.contains(protocol)
? protocol
: DUBBO_PROTOCOL;
}
public InternalServiceConfigBuilder<T> protocol(String protocol) {
this.protocol(protocol, null);
return getThis();
}
public InternalServiceConfigBuilder<T> port(Integer specPort) {
return port(specPort, null);
}
public InternalServiceConfigBuilder<T> port(Integer specPort, String key) {
Assert.notEmptyString(this.protocol, "export protocol is null");
Assert.notNull(this.interfaceClass, "export interfaceClass is null");
if (specPort != null) {
this.port = specPort;
return getThis();
}
Map<String, String> params = getApplicationConfig().getParameters();
if (CollectionUtils.isNotEmptyMap(params) && StringUtils.isNotBlank(key)) {
String rawPort = getApplicationConfig().getParameters().get(key);
if (StringUtils.isNotEmpty(rawPort)) {
specPort = Integer.parseInt(rawPort);
}
}
if (specPort == null || specPort < -1) {
try {
if (logger.isInfoEnabled()) {
logger.info(interfaceClass.getName()
+ "Service Port hasn't been set will use default protocol defined in protocols.");
}
Protocol protocol =
applicationModel.getExtensionLoader(Protocol.class).getExtension(this.protocol);
if (protocol != null && protocol.getServers() != null) {
Iterator<ProtocolServer> it = protocol.getServers().iterator();
// export service may export before normal service export, it.hasNext() will return false.
// so need use specified protocol port.
if (it.hasNext()) {
ProtocolServer server = it.next();
String rawPort = server.getUrl().getParameter(BIND_PORT_KEY);
if (rawPort == null) {
String addr = server.getAddress();
rawPort = addr.substring(addr.indexOf(":") + 1);
}
this.port = Integer.parseInt(rawPort);
} else {
ProtocolConfig specifiedProtocolConfig = getProtocolConfig();
if (specifiedProtocolConfig != null) {
Integer protocolPort = specifiedProtocolConfig.getPort();
if (null != protocolPort && protocolPort != -1) {
this.port = protocolPort;
}
}
}
}
} catch (Exception e) {
logger.error(
INTERNAL_ERROR,
"invalid specified " + port + " port, error " + e.getMessage(),
"",
"Failed to find any valid protocol, will use random port to export service.",
e);
}
}
if (this.port == null) {
this.port = -1;
}
return getThis();
}
private ProtocolConfig getProtocolConfig() {
return applicationModel
.getApplicationConfigManager()
.getProtocol(protocol)
.orElse(null);
}
public ServiceConfig<T> build(Consumer<ServiceConfig<T>> configConsumer) {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName(this.protocol);
protocolConfig.setPort(this.port);
this.nullAssert();
logger.info("Using " + this.protocol + " protocol to export " + interfaceClass.getName() + " service on port "
+ protocolConfig.getPort());
applicationModel
.getApplicationConfigManager()
.getProtocol(this.protocol)
.ifPresent(protocolConfig::mergeProtocol);
ApplicationConfig applicationConfig = getApplicationConfig();
ServiceConfig<T> serviceConfig = new ServiceConfig<>();
serviceConfig.setScopeModel(applicationModel.getInternalModule());
serviceConfig.setApplication(applicationConfig);
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.refresh();
registryConfig.setNeedRefresh(false);
registryConfig.setId(this.registryId);
registryConfig.setAddress("N/A");
registryConfig.setScopeModel(this.applicationModel);
serviceConfig.setRegistry(registryConfig);
serviceConfig.setRegister(false);
serviceConfig.setProtocol(protocolConfig);
serviceConfig.setDelay(0);
serviceConfig.setInterface(interfaceClass);
serviceConfig.setRef(this.ref);
serviceConfig.setGroup(applicationConfig.getName());
serviceConfig.setVersion("1.0.0");
serviceConfig.setFilter("-default");
serviceConfig.setExecutor(executor);
if (null != configConsumer) {
configConsumer.accept(serviceConfig);
}
return serviceConfig;
}
public ServiceConfig<T> build() {
return build(null);
}
private void nullAssert() {
Assert.notNull(port, "export service port is null");
Assert.notNull(protocol, "export service protocol is null");
Assert.notNull(interfaceClass, "export service interfaceClass is null");
Assert.notNull(ref, "export service ref is null");
Assert.notNull(registryId, "export service registryId is null");
}
protected InternalServiceConfigBuilder<T> getThis() {
return this;
}
private ApplicationConfig getApplicationConfig() {
return applicationModel.getApplicationConfigManager().getApplicationOrElseThrow();
}
}
| 8,596 |
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/ConfigCenterBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ConfigCenterConfig;
import java.util.Map;
/**
* This is a builder for build {@link ConfigCenterConfig}.
*
* @since 2.7
*/
public class ConfigCenterBuilder extends AbstractBuilder<ConfigCenterConfig, ConfigCenterBuilder> {
private String protocol;
private String address;
private String cluster;
private String namespace = "dubbo";
private String group = "dubbo";
private String username;
private String password;
private Long timeout = 3000L;
private Boolean highestPriority = true;
private Boolean check = true;
private String configFile = "dubbo.properties";
private String appConfigFile;
private Map<String, String> parameters;
public ConfigCenterBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public ConfigCenterBuilder address(String address) {
this.address = address;
return getThis();
}
public ConfigCenterBuilder cluster(String cluster) {
this.cluster = cluster;
return getThis();
}
public ConfigCenterBuilder namespace(String namespace) {
this.namespace = namespace;
return getThis();
}
public ConfigCenterBuilder group(String group) {
this.group = group;
return getThis();
}
public ConfigCenterBuilder username(String username) {
this.username = username;
return getThis();
}
public ConfigCenterBuilder password(String password) {
this.password = password;
return getThis();
}
public ConfigCenterBuilder timeout(Long timeout) {
this.timeout = timeout;
return getThis();
}
public ConfigCenterBuilder highestPriority(Boolean highestPriority) {
this.highestPriority = highestPriority;
return getThis();
}
public ConfigCenterBuilder check(Boolean check) {
this.check = check;
return getThis();
}
public ConfigCenterBuilder configFile(String configFile) {
this.configFile = configFile;
return getThis();
}
public ConfigCenterBuilder appConfigFile(String appConfigFile) {
this.appConfigFile = appConfigFile;
return getThis();
}
public ConfigCenterBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(this.parameters, appendParameters);
return getThis();
}
public ConfigCenterBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(this.parameters, key, value);
return getThis();
}
public ConfigCenterConfig build() {
ConfigCenterConfig configCenter = new ConfigCenterConfig();
super.build(configCenter);
configCenter.setProtocol(protocol);
configCenter.setAddress(address);
configCenter.setCluster(cluster);
configCenter.setNamespace(namespace);
configCenter.setGroup(group);
configCenter.setUsername(username);
configCenter.setPassword(password);
configCenter.setTimeout(timeout);
configCenter.setHighestPriority(highestPriority);
configCenter.setCheck(check);
configCenter.setConfigFile(configFile);
configCenter.setAppConfigFile(appConfigFile);
configCenter.setParameters(parameters);
return configCenter;
}
@Override
protected ConfigCenterBuilder getThis() {
return this;
}
}
| 8,597 |
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/ProtocolBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ProtocolConfig;
import java.util.Map;
/**
* This is a builder for build {@link ProtocolConfig}.
*
* @since 2.7
*/
public class ProtocolBuilder extends AbstractBuilder<ProtocolConfig, ProtocolBuilder> {
/**
* Protocol name
*/
private String name;
/**
* Service ip address (when there are multiple network cards available)
*/
private String host;
/**
* Service port
*/
private Integer port;
/**
* Context path
*/
private String contextpath;
/**
* Thread pool
*/
private String threadpool;
/**
* Thread pool core thread size
*/
private Integer corethreads;
/**
* Thread pool size (fixed size)
*/
private Integer threads;
/**
* IO thread pool size (fixed size)
*/
private Integer iothreads;
/**
* Thread pool's queue length
*/
private Integer queues;
/**
* Max acceptable connections
*/
private Integer accepts;
/**
* Protocol codec
*/
private String codec;
/**
* Serialization
*/
private String serialization;
/**
* Charset
*/
private String charset;
/**
* Payload max length
*/
private Integer payload;
/**
* Buffer size
*/
private Integer buffer;
/**
* Heartbeat interval
*/
private Integer heartbeat;
/**
* Access log
*/
private String accesslog;
/**
* Transporter
*/
private String transporter;
/**
* How information is exchanged
*/
private String exchanger;
/**
* Thread dispatch mode
*/
private String dispatcher;
/**
* Networker
*/
private String networker;
/**
* Sever impl
*/
private String server;
/**
* Client impl
*/
private String client;
/**
* Supported telnet commands, separated with comma.
*/
private String telnet;
/**
* Command line prompt
*/
private String prompt;
/**
* Status check
*/
private String status;
/**
* Whether to register
*/
private Boolean register;
/**
* whether it is a persistent connection
*/
// TODO add this to provider config
private Boolean keepAlive;
// TODO add this to provider config
private String optimizer;
/**
* The extension
*/
private String extension;
/**
* The customized parameters
*/
private Map<String, String> parameters;
/**
* If it's default
*/
private Boolean isDefault;
public static ProtocolBuilder newBuilder() {
return new ProtocolBuilder();
}
public ProtocolBuilder id(String id) {
return super.id(id);
}
public ProtocolBuilder name(String name) {
this.name = name;
return getThis();
}
public ProtocolBuilder host(String host) {
this.host = host;
return getThis();
}
public ProtocolBuilder port(Integer port) {
this.port = port;
return getThis();
}
public ProtocolBuilder contextpath(String contextpath) {
this.contextpath = contextpath;
return getThis();
}
/**
* @param path
* @return ProtocolBuilder
* @see ProtocolBuilder#contextpath(String)
*/
@Deprecated
public ProtocolBuilder path(String path) {
this.contextpath = path;
return getThis();
}
public ProtocolBuilder threadpool(String threadpool) {
this.threadpool = threadpool;
return getThis();
}
public ProtocolBuilder corethreads(Integer corethreads) {
this.corethreads = corethreads;
return getThis();
}
public ProtocolBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ProtocolBuilder iothreads(Integer iothreads) {
this.iothreads = iothreads;
return getThis();
}
public ProtocolBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ProtocolBuilder accepts(Integer accepts) {
this.accepts = accepts;
return getThis();
}
public ProtocolBuilder codec(String codec) {
this.codec = codec;
return getThis();
}
public ProtocolBuilder serialization(String serialization) {
this.serialization = serialization;
return getThis();
}
public ProtocolBuilder charset(String charset) {
this.charset = charset;
return getThis();
}
public ProtocolBuilder payload(Integer payload) {
this.payload = payload;
return getThis();
}
public ProtocolBuilder buffer(Integer buffer) {
this.buffer = buffer;
return getThis();
}
public ProtocolBuilder heartbeat(Integer heartbeat) {
this.heartbeat = heartbeat;
return getThis();
}
public ProtocolBuilder accesslog(String accesslog) {
this.accesslog = accesslog;
return getThis();
}
public ProtocolBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
public ProtocolBuilder exchanger(String exchanger) {
this.exchanger = exchanger;
return getThis();
}
public ProtocolBuilder dispatcher(String dispatcher) {
this.dispatcher = dispatcher;
return getThis();
}
/**
* @param dispather
* @return ProtocolBuilder
* @see ProtocolBuilder#dispatcher(String)
*/
@Deprecated
public ProtocolBuilder dispather(String dispather) {
this.dispatcher = dispather;
return getThis();
}
public ProtocolBuilder networker(String networker) {
this.networker = networker;
return getThis();
}
public ProtocolBuilder server(String server) {
this.server = server;
return getThis();
}
public ProtocolBuilder client(String client) {
this.client = client;
return getThis();
}
public ProtocolBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
}
public ProtocolBuilder prompt(String prompt) {
this.prompt = prompt;
return getThis();
}
public ProtocolBuilder status(String status) {
this.status = status;
return getThis();
}
public ProtocolBuilder register(Boolean register) {
this.register = register;
return getThis();
}
public ProtocolBuilder keepAlive(Boolean keepAlive) {
this.keepAlive = keepAlive;
return getThis();
}
public ProtocolBuilder optimizer(String optimizer) {
this.optimizer = optimizer;
return getThis();
}
public ProtocolBuilder extension(String extension) {
this.extension = extension;
return getThis();
}
public ProtocolBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public ProtocolBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public ProtocolBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ProtocolConfig build() {
ProtocolConfig protocolConfig = new ProtocolConfig();
super.build(protocolConfig);
protocolConfig.setAccepts(accepts);
protocolConfig.setAccesslog(accesslog);
protocolConfig.setBuffer(buffer);
protocolConfig.setCharset(charset);
protocolConfig.setClient(client);
protocolConfig.setCodec(codec);
protocolConfig.setContextpath(contextpath);
protocolConfig.setCorethreads(corethreads);
protocolConfig.setDefault(isDefault);
protocolConfig.setDispatcher(dispatcher);
protocolConfig.setExchanger(exchanger);
protocolConfig.setExtension(extension);
protocolConfig.setHeartbeat(heartbeat);
protocolConfig.setHost(host);
protocolConfig.setIothreads(iothreads);
protocolConfig.setKeepAlive(keepAlive);
protocolConfig.setName(name);
protocolConfig.setNetworker(networker);
protocolConfig.setOptimizer(optimizer);
protocolConfig.setParameters(parameters);
protocolConfig.setPayload(payload);
protocolConfig.setPort(port);
protocolConfig.setPrompt(prompt);
protocolConfig.setQueues(queues);
protocolConfig.setRegister(register);
protocolConfig.setSerialization(serialization);
protocolConfig.setServer(server);
protocolConfig.setStatus(status);
protocolConfig.setTelnet(telnet);
protocolConfig.setThreadpool(threadpool);
protocolConfig.setThreads(threads);
protocolConfig.setTransporter(transporter);
return protocolConfig;
}
@Override
protected ProtocolBuilder getThis() {
return this;
}
}
| 8,598 |
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/ProviderBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.ProviderConfig;
/**
* This is a builder for build {@link ProviderConfig}.
*
* @since 2.7
*/
public class ProviderBuilder extends AbstractServiceBuilder<ProviderConfig, ProviderBuilder> {
/**
* Service ip addresses (used when there are multiple network cards available)
*/
private String host;
/**
* Service port
*/
private Integer port;
/**
* Context path
*/
private String contextpath;
/**
* Thread pool
*/
private String threadpool;
/**
* Thread pool size (fixed size)
*/
private Integer threads;
/**
* IO thread pool size (fixed size)
*/
private Integer iothreads;
/**
* Thread pool queue length
*/
private Integer queues;
/**
* Max acceptable connections
*/
private Integer accepts;
/**
* Protocol codec
*/
private String codec;
/**
* The serialization charset
*/
private String charset;
/**
* Payload max length
*/
private Integer payload;
/**
* The network io buffer size
*/
private Integer buffer;
/**
* Transporter
*/
private String transporter;
/**
* How information gets exchanged
*/
private String exchanger;
/**
* Thread dispatching mode
*/
private String dispatcher;
/**
* Networker
*/
private String networker;
/**
* The server-side implementation model of the protocol
*/
private String server;
/**
* The client-side implementation model of the protocol
*/
private String client;
/**
* Supported telnet commands, separated with comma.
*/
private String telnet;
/**
* Command line prompt
*/
private String prompt;
/**
* Status check
*/
private String status;
/**
* Wait time when stop
*/
private Integer wait;
/**
* Whether to use the default protocol
*/
private Boolean isDefault;
public ProviderBuilder host(String host) {
this.host = host;
return getThis();
}
public ProviderBuilder port(Integer port) {
this.port = port;
return getThis();
}
public ProviderBuilder contextPath(String contextPath) {
this.contextpath = contextPath;
return getThis();
}
public ProviderBuilder threadPool(String threadPool) {
this.threadpool = threadPool;
return getThis();
}
public ProviderBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ProviderBuilder ioThreads(Integer ioThreads) {
this.iothreads = ioThreads;
return getThis();
}
public ProviderBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ProviderBuilder accepts(Integer accepts) {
this.accepts = accepts;
return getThis();
}
public ProviderBuilder codec(String codec) {
this.codec = codec;
return getThis();
}
public ProviderBuilder charset(String charset) {
this.charset = charset;
return getThis();
}
public ProviderBuilder payload(Integer payload) {
this.payload = payload;
return getThis();
}
public ProviderBuilder buffer(Integer buffer) {
this.buffer = buffer;
return getThis();
}
public ProviderBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
public ProviderBuilder exchanger(String exchanger) {
this.exchanger = exchanger;
return getThis();
}
public ProviderBuilder dispatcher(String dispatcher) {
this.dispatcher = dispatcher;
return getThis();
}
public ProviderBuilder networker(String networker) {
this.networker = networker;
return getThis();
}
public ProviderBuilder server(String server) {
this.server = server;
return getThis();
}
public ProviderBuilder client(String client) {
this.client = client;
return getThis();
}
public ProviderBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
}
public ProviderBuilder prompt(String prompt) {
this.prompt = prompt;
return getThis();
}
public ProviderBuilder status(String status) {
this.status = status;
return getThis();
}
public ProviderBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
}
public ProviderBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ProviderConfig build() {
ProviderConfig provider = new ProviderConfig();
super.build(provider);
provider.setHost(host);
provider.setPort(port);
provider.setContextpath(contextpath);
provider.setThreadpool(threadpool);
provider.setThreads(threads);
provider.setIothreads(iothreads);
provider.setQueues(queues);
provider.setAccepts(accepts);
provider.setCodec(codec);
provider.setPayload(payload);
provider.setCharset(charset);
provider.setBuffer(buffer);
provider.setTransporter(transporter);
provider.setExchanger(exchanger);
provider.setDispatcher(dispatcher);
provider.setNetworker(networker);
provider.setServer(server);
provider.setClient(client);
provider.setTelnet(telnet);
provider.setPrompt(prompt);
provider.setStatus(status);
provider.setWait(wait);
provider.setDefault(isDefault);
return provider;
}
@Override
protected ProviderBuilder getThis() {
return this;
}
}
| 8,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.