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-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
/**
* metadata report factory impl for nacos
*/
public class NacosMetadataReportFactory extends AbstractMetadataReportFactory {
@Override
protected MetadataReport createMetadataReport(URL url) {
return new NacosMetadataReport(url);
}
}
| 7,300 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosConfigServiceWrapper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.store.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
import static org.apache.dubbo.common.utils.StringUtils.SLASH_CHAR;
public class NacosConfigServiceWrapper {
private static final String INNERCLASS_SYMBOL = "$";
private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___";
private static final long DEFAULT_TIMEOUT = 3000L;
private ConfigService configService;
public NacosConfigServiceWrapper(ConfigService configService) {
this.configService = configService;
}
public ConfigService getConfigService() {
return configService;
}
public void addListener(String dataId, String group, Listener listener) throws NacosException {
configService.addListener(handleInnerSymbol(dataId), handleInnerSymbol(group), listener);
}
public void removeListener(String dataId, String group, Listener listener) throws NacosException {
configService.removeListener(handleInnerSymbol(dataId), handleInnerSymbol(group), listener);
}
public String getConfig(String dataId, String group) throws NacosException {
return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), DEFAULT_TIMEOUT);
}
public String getConfig(String dataId, String group, long timeout) throws NacosException {
return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), timeout);
}
public boolean publishConfig(String dataId, String group, String content) throws NacosException {
return configService.publishConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), content);
}
public boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException {
return configService.publishConfigCas(handleInnerSymbol(dataId), handleInnerSymbol(group), content, casMd5);
}
public boolean removeConfig(String dataId, String group) throws NacosException {
return configService.removeConfig(handleInnerSymbol(dataId), handleInnerSymbol(group));
}
/**
* see {@link com.alibaba.nacos.client.config.utils.ParamUtils#isValid(java.lang.String)}
*/
private String handleInnerSymbol(String data) {
if (data == null) {
return null;
}
return data.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL).replace(SLASH_CHAR, HYPHEN_CHAR);
}
}
| 7,301 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.definition.protobuf;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.definition.model.MethodDefinition;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.metadata.definition.protobuf.model.ServiceInterface;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* 2019-07-01
*/
class ProtobufTypeBuilderTest {
@Test
void testProtobufBuilder() {
TypeDefinitionBuilder.initBuilders(FrameworkModel.defaultModel());
// TEST Pb Service metaData builder
FullServiceDefinition serviceDefinition = ServiceDefinitionBuilder.buildFullDefinition(ServiceInterface.class);
MethodDefinition methodDefinition = serviceDefinition.getMethods().get(0);
List<TypeDefinition> types = serviceDefinition.getTypes();
String parameterName = methodDefinition.getParameterTypes()[0];
TypeDefinition typeDefinition = null;
for (TypeDefinition type : serviceDefinition.getTypes()) {
if (parameterName.equals(type.getType())) {
typeDefinition = type;
break;
}
}
Map<String, String> propertiesMap = typeDefinition.getProperties();
assertThat(propertiesMap.size(), is(11));
assertThat(propertiesMap.containsKey("money"), is(true));
assertThat(getTypeName(propertiesMap.get("money"), types), equalTo("double"));
assertThat(propertiesMap.containsKey("cash"), is(true));
assertThat(getTypeName(propertiesMap.get("cash"), types), equalTo("float"));
assertThat(propertiesMap.containsKey("age"), is(true));
assertThat(getTypeName(propertiesMap.get("age"), types), equalTo("int"));
assertThat(propertiesMap.containsKey("num"), is(true));
assertThat(getTypeName(propertiesMap.get("num"), types), equalTo("long"));
assertThat(propertiesMap.containsKey("sex"), is(true));
assertThat(getTypeName(propertiesMap.get("sex"), types), equalTo("boolean"));
assertThat(propertiesMap.containsKey("name"), is(true));
assertThat(getTypeName(propertiesMap.get("name"), types), equalTo("java.lang.String"));
assertThat(propertiesMap.containsKey("msg"), is(true));
assertThat(getTypeName(propertiesMap.get("msg"), types), equalTo("com.google.protobuf.ByteString"));
assertThat(propertiesMap.containsKey("phone"), is(true));
assertThat(
getTypeName(propertiesMap.get("phone"), types),
equalTo("java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>"));
assertThat(propertiesMap.containsKey("doubleMap"), is(true));
assertThat(
getTypeName(propertiesMap.get("doubleMap"), types),
equalTo(
"java.util.Map<java.lang.String,org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>"));
assertThat(
getTypeName(propertiesMap.get("bytesList"), types),
equalTo("java.util.List<com.google.protobuf.ByteString>"));
assertThat(
getTypeName(propertiesMap.get("bytesMap"), types),
equalTo("java.util.Map<java.lang.String,com.google.protobuf.ByteString>"));
}
private static String getTypeName(String type, List<TypeDefinition> types) {
for (TypeDefinition typeDefinition : types) {
if (type.equals(typeDefinition.getType())) {
return typeDefinition.getType();
}
}
return type;
}
}
| 7,302 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/ServiceInterface.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.definition.protobuf.model;
public interface ServiceInterface {
GooglePB.PBResponseType sayHello(GooglePB.PBRequestType requestType);
}
| 7,303 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/GooglePB.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.definition.protobuf.model;
public final class GooglePB {
private GooglePB() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
/**
* Protobuf enum {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneType}
*/
public enum PhoneType implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>MOBILE = 0;</code>
*/
MOBILE(0),
/**
* <code>HOME = 1;</code>
*/
HOME(1),
/**
* <code>WORK = 2;</code>
*/
WORK(2),
;
/**
* <code>MOBILE = 0;</code>
*/
public static final int MOBILE_VALUE = 0;
/**
* <code>HOME = 1;</code>
*/
public static final int HOME_VALUE = 1;
/**
* <code>WORK = 2;</code>
*/
public static final int WORK_VALUE = 2;
public final int getNumber() {
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static PhoneType valueOf(int value) {
return forNumber(value);
}
public static PhoneType forNumber(int value) {
switch (value) {
case 0:
return MOBILE;
case 1:
return HOME;
case 2:
return WORK;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<PhoneType> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<PhoneType> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<PhoneType>() {
public PhoneType findValueByNumber(int number) {
return PhoneType.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final PhoneType[] VALUES = values();
public static PhoneType valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
return VALUES[desc.getIndex()];
}
private final int value;
private PhoneType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneType)
}
public interface PBRequestTypeOrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional double money = 1;</code>
*/
boolean hasMoney();
/**
* <code>optional double money = 1;</code>
*/
double getMoney();
/**
* <code>optional float cash = 2;</code>
*/
boolean hasCash();
/**
* <code>optional float cash = 2;</code>
*/
float getCash();
/**
* <code>optional int32 age = 3;</code>
*/
boolean hasAge();
/**
* <code>optional int32 age = 3;</code>
*/
int getAge();
/**
* <code>optional int64 num = 4;</code>
*/
boolean hasNum();
/**
* <code>optional int64 num = 4;</code>
*/
long getNum();
/**
* <code>optional bool sex = 5;</code>
*/
boolean hasSex();
/**
* <code>optional bool sex = 5;</code>
*/
boolean getSex();
/**
* <code>optional string name = 6;</code>
*/
boolean hasName();
/**
* <code>optional string name = 6;</code>
*/
java.lang.String getName();
/**
* <code>optional string name = 6;</code>
*/
com.google.protobuf.ByteString getNameBytes();
/**
* <code>optional bytes msg = 7;</code>
*/
boolean hasMsg();
/**
* <code>optional bytes msg = 7;</code>
*/
com.google.protobuf.ByteString getMsg();
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> getPhoneList();
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index);
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
int getPhoneCount();
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
java.util.List<? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder>
getPhoneOrBuilderList();
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder(int index);
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
int getDoubleMapCount();
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
boolean containsDoubleMap(java.lang.String key);
/**
* Use {@link #getDoubleMapMap()} instead.
*/
@java.lang.Deprecated
java.util.Map<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getDoubleMap();
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
java.util.Map<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getDoubleMapMap();
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault(
java.lang.String key,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue);
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow(
java.lang.String key);
/**
* <code>repeated bytes bytesList = 10;</code>
*/
java.util.List<com.google.protobuf.ByteString> getBytesListList();
/**
* <code>repeated bytes bytesList = 10;</code>
*/
int getBytesListCount();
/**
* <code>repeated bytes bytesList = 10;</code>
*/
com.google.protobuf.ByteString getBytesList(int index);
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
int getBytesMapCount();
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
boolean containsBytesMap(java.lang.String key);
/**
* Use {@link #getBytesMapMap()} instead.
*/
@java.lang.Deprecated
java.util.Map<java.lang.String, com.google.protobuf.ByteString> getBytesMap();
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
java.util.Map<java.lang.String, com.google.protobuf.ByteString> getBytesMapMap();
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
com.google.protobuf.ByteString getBytesMapOrDefault(
java.lang.String key, com.google.protobuf.ByteString defaultValue);
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
com.google.protobuf.ByteString getBytesMapOrThrow(java.lang.String key);
}
/**
* Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType}
*/
public static final class PBRequestType extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType)
PBRequestTypeOrBuilder {
private static final long serialVersionUID = 0L;
// Use PBRequestType.newBuilder() to construct.
private PBRequestType(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PBRequestType() {
money_ = 0D;
cash_ = 0F;
age_ = 0;
num_ = 0L;
sex_ = false;
name_ = "";
msg_ = com.google.protobuf.ByteString.EMPTY;
phone_ = java.util.Collections.emptyList();
bytesList_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private PBRequestType(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 9: {
bitField0_ |= 0x00000001;
money_ = input.readDouble();
break;
}
case 21: {
bitField0_ |= 0x00000002;
cash_ = input.readFloat();
break;
}
case 24: {
bitField0_ |= 0x00000004;
age_ = input.readInt32();
break;
}
case 32: {
bitField0_ |= 0x00000008;
num_ = input.readInt64();
break;
}
case 40: {
bitField0_ |= 0x00000010;
sex_ = input.readBool();
break;
}
case 50: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000020;
name_ = bs;
break;
}
case 58: {
bitField0_ |= 0x00000040;
msg_ = input.readBytes();
break;
}
case 66: {
if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) {
phone_ = new java.util.ArrayList<
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>();
mutable_bitField0_ |= 0x00000080;
}
phone_.add(input.readMessage(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.PARSER,
extensionRegistry));
break;
}
case 74: {
if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) {
doubleMap_ = com.google.protobuf.MapField.newMapField(
DoubleMapDefaultEntryHolder.defaultEntry);
mutable_bitField0_ |= 0x00000100;
}
com.google.protobuf.MapEntry<String, PhoneNumber> doubleMap__ = input.readMessage(
DoubleMapDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry);
doubleMap_.getMutableMap().put(doubleMap__.getKey(), doubleMap__.getValue());
break;
}
case 82: {
if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) {
bytesList_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
mutable_bitField0_ |= 0x00000200;
}
bytesList_.add(input.readBytes());
break;
}
case 90: {
if (!((mutable_bitField0_ & 0x00000400) == 0x00000400)) {
bytesMap_ = com.google.protobuf.MapField.newMapField(
BytesMapDefaultEntryHolder.defaultEntry);
mutable_bitField0_ |= 0x00000400;
}
com.google.protobuf.MapEntry<String, com.google.protobuf.ByteString> bytesMap__ =
input.readMessage(
BytesMapDefaultEntryHolder.defaultEntry.getParserForType(),
extensionRegistry);
bytesMap_.getMutableMap().put(bytesMap__.getKey(), bytesMap__.getValue());
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) {
phone_ = java.util.Collections.unmodifiableList(phone_);
}
if (((mutable_bitField0_ & 0x00000200) == 0x00000200)) {
bytesList_ = java.util.Collections.unmodifiableList(bytesList_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 9:
return internalGetDoubleMap();
case 11:
return internalGetBytesMap();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.class,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder.class);
}
private int bitField0_;
public static final int MONEY_FIELD_NUMBER = 1;
private double money_;
/**
* <code>optional double money = 1;</code>
*/
public boolean hasMoney() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional double money = 1;</code>
*/
public double getMoney() {
return money_;
}
public static final int CASH_FIELD_NUMBER = 2;
private float cash_;
/**
* <code>optional float cash = 2;</code>
*/
public boolean hasCash() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional float cash = 2;</code>
*/
public float getCash() {
return cash_;
}
public static final int AGE_FIELD_NUMBER = 3;
private int age_;
/**
* <code>optional int32 age = 3;</code>
*/
public boolean hasAge() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional int32 age = 3;</code>
*/
public int getAge() {
return age_;
}
public static final int NUM_FIELD_NUMBER = 4;
private long num_;
/**
* <code>optional int64 num = 4;</code>
*/
public boolean hasNum() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional int64 num = 4;</code>
*/
public long getNum() {
return num_;
}
public static final int SEX_FIELD_NUMBER = 5;
private boolean sex_;
/**
* <code>optional bool sex = 5;</code>
*/
public boolean hasSex() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional bool sex = 5;</code>
*/
public boolean getSex() {
return sex_;
}
public static final int NAME_FIELD_NUMBER = 6;
private volatile java.lang.Object name_;
/**
* <code>optional string name = 6;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string name = 6;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <code>optional string name = 6;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int MSG_FIELD_NUMBER = 7;
private com.google.protobuf.ByteString msg_;
/**
* <code>optional bytes msg = 7;</code>
*/
public boolean hasMsg() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bytes msg = 7;</code>
*/
public com.google.protobuf.ByteString getMsg() {
return msg_;
}
public static final int PHONE_FIELD_NUMBER = 8;
private java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> phone_;
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> getPhoneList() {
return phone_;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public java.util.List<
? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder>
getPhoneOrBuilderList() {
return phone_;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public int getPhoneCount() {
return phone_.size();
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index) {
return phone_.get(index);
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder(
int index) {
return phone_.get(index);
}
public static final int DOUBLEMAP_FIELD_NUMBER = 9;
private static final class DoubleMapDefaultEntryHolder {
static final com.google.protobuf.MapEntry<String, PhoneNumber> defaultEntry = com.google.protobuf.MapEntry
.<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
newDefaultInstance(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.MESSAGE,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber
.getDefaultInstance());
}
private com.google.protobuf.MapField<String, PhoneNumber> doubleMap_;
private com.google.protobuf.MapField<String, PhoneNumber> internalGetDoubleMap() {
if (doubleMap_ == null) {
return com.google.protobuf.MapField.emptyMapField(DoubleMapDefaultEntryHolder.defaultEntry);
}
return doubleMap_;
}
public int getDoubleMapCount() {
return internalGetDoubleMap().getMap().size();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public boolean containsDoubleMap(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
return internalGetDoubleMap().getMap().containsKey(key);
}
/**
* Use {@link #getDoubleMapMap()} instead.
*/
@java.lang.Deprecated
public java.util.Map<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getDoubleMap() {
return getDoubleMapMap();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public java.util.Map<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getDoubleMapMap() {
return internalGetDoubleMap().getMap();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault(
java.lang.String key,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
map = internalGetDoubleMap().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow(
java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
map = internalGetDoubleMap().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public static final int BYTESLIST_FIELD_NUMBER = 10;
private java.util.List<com.google.protobuf.ByteString> bytesList_;
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public java.util.List<com.google.protobuf.ByteString> getBytesListList() {
return bytesList_;
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public int getBytesListCount() {
return bytesList_.size();
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public com.google.protobuf.ByteString getBytesList(int index) {
return bytesList_.get(index);
}
public static final int BYTESMAP_FIELD_NUMBER = 11;
private static final class BytesMapDefaultEntryHolder {
static final com.google.protobuf.MapEntry<String, com.google.protobuf.ByteString> defaultEntry =
com.google.protobuf.MapEntry.<java.lang.String, com.google.protobuf.ByteString>newDefaultInstance(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.BYTES,
com.google.protobuf.ByteString.EMPTY);
}
private com.google.protobuf.MapField<String, com.google.protobuf.ByteString> bytesMap_;
private com.google.protobuf.MapField<String, com.google.protobuf.ByteString> internalGetBytesMap() {
if (bytesMap_ == null) {
return com.google.protobuf.MapField.emptyMapField(BytesMapDefaultEntryHolder.defaultEntry);
}
return bytesMap_;
}
public int getBytesMapCount() {
return internalGetBytesMap().getMap().size();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public boolean containsBytesMap(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
return internalGetBytesMap().getMap().containsKey(key);
}
/**
* Use {@link #getBytesMapMap()} instead.
*/
@java.lang.Deprecated
public java.util.Map<java.lang.String, com.google.protobuf.ByteString> getBytesMap() {
return getBytesMapMap();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public java.util.Map<java.lang.String, com.google.protobuf.ByteString> getBytesMapMap() {
return internalGetBytesMap().getMap();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public com.google.protobuf.ByteString getBytesMapOrDefault(
java.lang.String key, com.google.protobuf.ByteString defaultValue) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, com.google.protobuf.ByteString> map =
internalGetBytesMap().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public com.google.protobuf.ByteString getBytesMapOrThrow(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, com.google.protobuf.ByteString> map =
internalGetBytesMap().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
for (int i = 0; i < getPhoneCount(); i++) {
if (!getPhone(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
for (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber item :
getDoubleMapMap().values()) {
if (!item.isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeDouble(1, money_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeFloat(2, cash_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeInt32(3, age_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeInt64(4, num_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBool(5, sex_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, name_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBytes(7, msg_);
}
for (int i = 0; i < phone_.size(); i++) {
output.writeMessage(8, phone_.get(i));
}
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetDoubleMap(), DoubleMapDefaultEntryHolder.defaultEntry, 9);
for (int i = 0; i < bytesList_.size(); i++) {
output.writeBytes(10, bytesList_.get(i));
}
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetBytesMap(), BytesMapDefaultEntryHolder.defaultEntry, 11);
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream.computeDoubleSize(1, money_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(2, cash_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, age_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(4, num_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(5, sex_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, name_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(7, msg_);
}
for (int i = 0; i < phone_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(8, phone_.get(i));
}
for (java.util.Map.Entry<
java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
entry : internalGetDoubleMap().getMap().entrySet()) {
com.google.protobuf.MapEntry<String, PhoneNumber> doubleMap__ = DoubleMapDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(9, doubleMap__);
}
{
int dataSize = 0;
for (int i = 0; i < bytesList_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream.computeBytesSizeNoTag(bytesList_.get(i));
}
size += dataSize;
size += 1 * getBytesListList().size();
}
for (java.util.Map.Entry<java.lang.String, com.google.protobuf.ByteString> entry :
internalGetBytesMap().getMap().entrySet()) {
com.google.protobuf.MapEntry<String, com.google.protobuf.ByteString> bytesMap__ =
BytesMapDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(11, bytesMap__);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType)) {
return super.equals(obj);
}
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType other =
(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) obj;
boolean result = true;
result = result && (hasMoney() == other.hasMoney());
if (hasMoney()) {
result = result
&& (java.lang.Double.doubleToLongBits(getMoney())
== java.lang.Double.doubleToLongBits(other.getMoney()));
}
result = result && (hasCash() == other.hasCash());
if (hasCash()) {
result = result
&& (java.lang.Float.floatToIntBits(getCash())
== java.lang.Float.floatToIntBits(other.getCash()));
}
result = result && (hasAge() == other.hasAge());
if (hasAge()) {
result = result && (getAge() == other.getAge());
}
result = result && (hasNum() == other.hasNum());
if (hasNum()) {
result = result && (getNum() == other.getNum());
}
result = result && (hasSex() == other.hasSex());
if (hasSex()) {
result = result && (getSex() == other.getSex());
}
result = result && (hasName() == other.hasName());
if (hasName()) {
result = result && getName().equals(other.getName());
}
result = result && (hasMsg() == other.hasMsg());
if (hasMsg()) {
result = result && getMsg().equals(other.getMsg());
}
result = result && getPhoneList().equals(other.getPhoneList());
result = result && internalGetDoubleMap().equals(other.internalGetDoubleMap());
result = result && getBytesListList().equals(other.getBytesListList());
result = result && internalGetBytesMap().equals(other.internalGetBytesMap());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasMoney()) {
hash = (37 * hash) + MONEY_FIELD_NUMBER;
hash = (53 * hash)
+ com.google.protobuf.Internal.hashLong(java.lang.Double.doubleToLongBits(getMoney()));
}
if (hasCash()) {
hash = (37 * hash) + CASH_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getCash());
}
if (hasAge()) {
hash = (37 * hash) + AGE_FIELD_NUMBER;
hash = (53 * hash) + getAge();
}
if (hasNum()) {
hash = (37 * hash) + NUM_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getNum());
}
if (hasSex()) {
hash = (37 * hash) + SEX_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSex());
}
if (hasName()) {
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
}
if (hasMsg()) {
hash = (37 * hash) + MSG_FIELD_NUMBER;
hash = (53 * hash) + getMsg().hashCode();
}
if (getPhoneCount() > 0) {
hash = (37 * hash) + PHONE_FIELD_NUMBER;
hash = (53 * hash) + getPhoneList().hashCode();
}
if (!internalGetDoubleMap().getMap().isEmpty()) {
hash = (37 * hash) + DOUBLEMAP_FIELD_NUMBER;
hash = (53 * hash) + internalGetDoubleMap().hashCode();
}
if (getBytesListCount() > 0) {
hash = (37 * hash) + BYTESLIST_FIELD_NUMBER;
hash = (53 * hash) + getBytesListList().hashCode();
}
if (!internalGetBytesMap().getMap().isEmpty()) {
hash = (37 * hash) + BYTESMAP_FIELD_NUMBER;
hash = (53 * hash) + internalGetBytesMap().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType)
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 9:
return internalGetDoubleMap();
case 11:
return internalGetBytesMap();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMutableMapField(int number) {
switch (number) {
case 9:
return internalGetMutableDoubleMap();
case 11:
return internalGetMutableBytesMap();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.class,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder
.class);
}
// Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPhoneFieldBuilder();
}
}
public Builder clear() {
super.clear();
money_ = 0D;
bitField0_ = (bitField0_ & ~0x00000001);
cash_ = 0F;
bitField0_ = (bitField0_ & ~0x00000002);
age_ = 0;
bitField0_ = (bitField0_ & ~0x00000004);
num_ = 0L;
bitField0_ = (bitField0_ & ~0x00000008);
sex_ = false;
bitField0_ = (bitField0_ & ~0x00000010);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000020);
msg_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000040);
if (phoneBuilder_ == null) {
phone_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000080);
} else {
phoneBuilder_.clear();
}
internalGetMutableDoubleMap().clear();
bytesList_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000200);
internalGetMutableBytesMap().clear();
return this;
}
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType
getDefaultInstanceForType() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance();
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType build() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType buildPartial() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType result =
new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.money_ = money_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.cash_ = cash_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.age_ = age_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.num_ = num_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.sex_ = sex_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.name_ = name_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.msg_ = msg_;
if (phoneBuilder_ == null) {
if (((bitField0_ & 0x00000080) == 0x00000080)) {
phone_ = java.util.Collections.unmodifiableList(phone_);
bitField0_ = (bitField0_ & ~0x00000080);
}
result.phone_ = phone_;
} else {
result.phone_ = phoneBuilder_.build();
}
result.doubleMap_ = internalGetDoubleMap();
result.doubleMap_.makeImmutable();
if (((bitField0_ & 0x00000200) == 0x00000200)) {
bytesList_ = java.util.Collections.unmodifiableList(bytesList_);
bitField0_ = (bitField0_ & ~0x00000200);
}
result.bytesList_ = bytesList_;
result.bytesMap_ = internalGetBytesMap();
result.bytesMap_.makeImmutable();
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) {
return mergeFrom(
(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType other) {
if (other
== org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType
.getDefaultInstance()) return this;
if (other.hasMoney()) {
setMoney(other.getMoney());
}
if (other.hasCash()) {
setCash(other.getCash());
}
if (other.hasAge()) {
setAge(other.getAge());
}
if (other.hasNum()) {
setNum(other.getNum());
}
if (other.hasSex()) {
setSex(other.getSex());
}
if (other.hasName()) {
bitField0_ |= 0x00000020;
name_ = other.name_;
onChanged();
}
if (other.hasMsg()) {
setMsg(other.getMsg());
}
if (phoneBuilder_ == null) {
if (!other.phone_.isEmpty()) {
if (phone_.isEmpty()) {
phone_ = other.phone_;
bitField0_ = (bitField0_ & ~0x00000080);
} else {
ensurePhoneIsMutable();
phone_.addAll(other.phone_);
}
onChanged();
}
} else {
if (!other.phone_.isEmpty()) {
if (phoneBuilder_.isEmpty()) {
phoneBuilder_.dispose();
phoneBuilder_ = null;
phone_ = other.phone_;
bitField0_ = (bitField0_ & ~0x00000080);
phoneBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getPhoneFieldBuilder()
: null;
} else {
phoneBuilder_.addAllMessages(other.phone_);
}
}
}
internalGetMutableDoubleMap().mergeFrom(other.internalGetDoubleMap());
if (!other.bytesList_.isEmpty()) {
if (bytesList_.isEmpty()) {
bytesList_ = other.bytesList_;
bitField0_ = (bitField0_ & ~0x00000200);
} else {
ensureBytesListIsMutable();
bytesList_.addAll(other.bytesList_);
}
onChanged();
}
internalGetMutableBytesMap().mergeFrom(other.internalGetBytesMap());
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
for (int i = 0; i < getPhoneCount(); i++) {
if (!getPhone(i).isInitialized()) {
return false;
}
}
for (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber item :
getDoubleMapMap().values()) {
if (!item.isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private double money_;
/**
* <code>optional double money = 1;</code>
*/
public boolean hasMoney() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional double money = 1;</code>
*/
public double getMoney() {
return money_;
}
/**
* <code>optional double money = 1;</code>
*/
public Builder setMoney(double value) {
bitField0_ |= 0x00000001;
money_ = value;
onChanged();
return this;
}
/**
* <code>optional double money = 1;</code>
*/
public Builder clearMoney() {
bitField0_ = (bitField0_ & ~0x00000001);
money_ = 0D;
onChanged();
return this;
}
private float cash_;
/**
* <code>optional float cash = 2;</code>
*/
public boolean hasCash() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional float cash = 2;</code>
*/
public float getCash() {
return cash_;
}
/**
* <code>optional float cash = 2;</code>
*/
public Builder setCash(float value) {
bitField0_ |= 0x00000002;
cash_ = value;
onChanged();
return this;
}
/**
* <code>optional float cash = 2;</code>
*/
public Builder clearCash() {
bitField0_ = (bitField0_ & ~0x00000002);
cash_ = 0F;
onChanged();
return this;
}
private int age_;
/**
* <code>optional int32 age = 3;</code>
*/
public boolean hasAge() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional int32 age = 3;</code>
*/
public int getAge() {
return age_;
}
/**
* <code>optional int32 age = 3;</code>
*/
public Builder setAge(int value) {
bitField0_ |= 0x00000004;
age_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 age = 3;</code>
*/
public Builder clearAge() {
bitField0_ = (bitField0_ & ~0x00000004);
age_ = 0;
onChanged();
return this;
}
private long num_;
/**
* <code>optional int64 num = 4;</code>
*/
public boolean hasNum() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional int64 num = 4;</code>
*/
public long getNum() {
return num_;
}
/**
* <code>optional int64 num = 4;</code>
*/
public Builder setNum(long value) {
bitField0_ |= 0x00000008;
num_ = value;
onChanged();
return this;
}
/**
* <code>optional int64 num = 4;</code>
*/
public Builder clearNum() {
bitField0_ = (bitField0_ & ~0x00000008);
num_ = 0L;
onChanged();
return this;
}
private boolean sex_;
/**
* <code>optional bool sex = 5;</code>
*/
public boolean hasSex() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>optional bool sex = 5;</code>
*/
public boolean getSex() {
return sex_;
}
/**
* <code>optional bool sex = 5;</code>
*/
public Builder setSex(boolean value) {
bitField0_ |= 0x00000010;
sex_ = value;
onChanged();
return this;
}
/**
* <code>optional bool sex = 5;</code>
*/
public Builder clearSex() {
bitField0_ = (bitField0_ & ~0x00000010);
sex_ = false;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
* <code>optional string name = 6;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string name = 6;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string name = 6;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string name = 6;</code>
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
name_ = value;
onChanged();
return this;
}
/**
* <code>optional string name = 6;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000020);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>optional string name = 6;</code>
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
name_ = value;
onChanged();
return this;
}
private com.google.protobuf.ByteString msg_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>optional bytes msg = 7;</code>
*/
public boolean hasMsg() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional bytes msg = 7;</code>
*/
public com.google.protobuf.ByteString getMsg() {
return msg_;
}
/**
* <code>optional bytes msg = 7;</code>
*/
public Builder setMsg(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000040;
msg_ = value;
onChanged();
return this;
}
/**
* <code>optional bytes msg = 7;</code>
*/
public Builder clearMsg() {
bitField0_ = (bitField0_ & ~0x00000040);
msg_ = getDefaultInstance().getMsg();
onChanged();
return this;
}
private java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber> phone_ =
java.util.Collections.emptyList();
private void ensurePhoneIsMutable() {
if (!((bitField0_ & 0x00000080) == 0x00000080)) {
phone_ = new java.util.ArrayList<
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>(phone_);
bitField0_ |= 0x00000080;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder>
phoneBuilder_;
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getPhoneList() {
if (phoneBuilder_ == null) {
return java.util.Collections.unmodifiableList(phone_);
} else {
return phoneBuilder_.getMessageList();
}
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public int getPhoneCount() {
if (phoneBuilder_ == null) {
return phone_.size();
} else {
return phoneBuilder_.getCount();
}
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getPhone(int index) {
if (phoneBuilder_ == null) {
return phone_.get(index);
} else {
return phoneBuilder_.getMessage(index);
}
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder setPhone(
int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) {
if (phoneBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePhoneIsMutable();
phone_.set(index, value);
onChanged();
} else {
phoneBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder setPhone(
int index,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) {
if (phoneBuilder_ == null) {
ensurePhoneIsMutable();
phone_.set(index, builderForValue.build());
onChanged();
} else {
phoneBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder addPhone(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) {
if (phoneBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePhoneIsMutable();
phone_.add(value);
onChanged();
} else {
phoneBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder addPhone(
int index, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) {
if (phoneBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePhoneIsMutable();
phone_.add(index, value);
onChanged();
} else {
phoneBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder addPhone(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) {
if (phoneBuilder_ == null) {
ensurePhoneIsMutable();
phone_.add(builderForValue.build());
onChanged();
} else {
phoneBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder addPhone(
int index,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder builderForValue) {
if (phoneBuilder_ == null) {
ensurePhoneIsMutable();
phone_.add(index, builderForValue.build());
onChanged();
} else {
phoneBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder addAllPhone(
java.lang.Iterable<
? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
values) {
if (phoneBuilder_ == null) {
ensurePhoneIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, phone_);
onChanged();
} else {
phoneBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder clearPhone() {
if (phoneBuilder_ == null) {
phone_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000080);
onChanged();
} else {
phoneBuilder_.clear();
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public Builder removePhone(int index) {
if (phoneBuilder_ == null) {
ensurePhoneIsMutable();
phone_.remove(index);
onChanged();
} else {
phoneBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder getPhoneBuilder(
int index) {
return getPhoneFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder getPhoneOrBuilder(
int index) {
if (phoneBuilder_ == null) {
return phone_.get(index);
} else {
return phoneBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public java.util.List<
? extends org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder>
getPhoneOrBuilderList() {
if (phoneBuilder_ != null) {
return phoneBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(phone_);
}
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder addPhoneBuilder() {
return getPhoneFieldBuilder()
.addBuilder(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber
.getDefaultInstance());
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder addPhoneBuilder(
int index) {
return getPhoneFieldBuilder()
.addBuilder(
index,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber
.getDefaultInstance());
}
/**
* <code>repeated .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber phone = 8;</code>
*/
public java.util.List<org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder>
getPhoneBuilderList() {
return getPhoneFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder>
getPhoneFieldBuilder() {
if (phoneBuilder_ == null) {
phoneBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
PhoneNumber, PhoneNumber.Builder, PhoneNumberOrBuilder>(
phone_, ((bitField0_ & 0x00000080) == 0x00000080), getParentForChildren(), isClean());
phone_ = null;
}
return phoneBuilder_;
}
private com.google.protobuf.MapField<String, PhoneNumber> doubleMap_;
private com.google.protobuf.MapField<String, PhoneNumber> internalGetDoubleMap() {
if (doubleMap_ == null) {
return com.google.protobuf.MapField.emptyMapField(DoubleMapDefaultEntryHolder.defaultEntry);
}
return doubleMap_;
}
private com.google.protobuf.MapField<String, PhoneNumber> internalGetMutableDoubleMap() {
onChanged();
;
if (doubleMap_ == null) {
doubleMap_ = com.google.protobuf.MapField.newMapField(DoubleMapDefaultEntryHolder.defaultEntry);
}
if (!doubleMap_.isMutable()) {
doubleMap_ = doubleMap_.copy();
}
return doubleMap_;
}
public int getDoubleMapCount() {
return internalGetDoubleMap().getMap().size();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public boolean containsDoubleMap(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
return internalGetDoubleMap().getMap().containsKey(key);
}
/**
* Use {@link #getDoubleMapMap()} instead.
*/
@java.lang.Deprecated
public java.util.Map<
java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getDoubleMap() {
return getDoubleMapMap();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public java.util.Map<
java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getDoubleMapMap() {
return internalGetDoubleMap().getMap();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrDefault(
java.lang.String key,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber defaultValue) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<
java.lang.String,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
map = internalGetDoubleMap().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDoubleMapOrThrow(
java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<
java.lang.String,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
map = internalGetDoubleMap().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public Builder clearDoubleMap() {
internalGetMutableDoubleMap().getMutableMap().clear();
return this;
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public Builder removeDoubleMap(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
internalGetMutableDoubleMap().getMutableMap().remove(key);
return this;
}
/**
* Use alternate mutation accessors instead.
*/
@java.lang.Deprecated
public java.util.Map<
java.lang.String, org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
getMutableDoubleMap() {
return internalGetMutableDoubleMap().getMutableMap();
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public Builder putDoubleMap(
java.lang.String key,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber value) {
if (key == null) {
throw new java.lang.NullPointerException();
}
if (value == null) {
throw new java.lang.NullPointerException();
}
internalGetMutableDoubleMap().getMutableMap().put(key, value);
return this;
}
/**
* <code>map<string, .org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber> doubleMap = 9;</code>
*/
public Builder putAllDoubleMap(
java.util.Map<
java.lang.String,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber>
values) {
internalGetMutableDoubleMap().getMutableMap().putAll(values);
return this;
}
private java.util.List<com.google.protobuf.ByteString> bytesList_ = java.util.Collections.emptyList();
private void ensureBytesListIsMutable() {
if (!((bitField0_ & 0x00000200) == 0x00000200)) {
bytesList_ = new java.util.ArrayList<com.google.protobuf.ByteString>(bytesList_);
bitField0_ |= 0x00000200;
}
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public java.util.List<com.google.protobuf.ByteString> getBytesListList() {
return java.util.Collections.unmodifiableList(bytesList_);
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public int getBytesListCount() {
return bytesList_.size();
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public com.google.protobuf.ByteString getBytesList(int index) {
return bytesList_.get(index);
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public Builder setBytesList(int index, com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
ensureBytesListIsMutable();
bytesList_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public Builder addBytesList(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
ensureBytesListIsMutable();
bytesList_.add(value);
onChanged();
return this;
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public Builder addAllBytesList(java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
ensureBytesListIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, bytesList_);
onChanged();
return this;
}
/**
* <code>repeated bytes bytesList = 10;</code>
*/
public Builder clearBytesList() {
bytesList_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000200);
onChanged();
return this;
}
private com.google.protobuf.MapField<String, com.google.protobuf.ByteString> bytesMap_;
private com.google.protobuf.MapField<String, com.google.protobuf.ByteString> internalGetBytesMap() {
if (bytesMap_ == null) {
return com.google.protobuf.MapField.emptyMapField(BytesMapDefaultEntryHolder.defaultEntry);
}
return bytesMap_;
}
private com.google.protobuf.MapField<String, com.google.protobuf.ByteString> internalGetMutableBytesMap() {
onChanged();
;
if (bytesMap_ == null) {
bytesMap_ = com.google.protobuf.MapField.newMapField(BytesMapDefaultEntryHolder.defaultEntry);
}
if (!bytesMap_.isMutable()) {
bytesMap_ = bytesMap_.copy();
}
return bytesMap_;
}
public int getBytesMapCount() {
return internalGetBytesMap().getMap().size();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public boolean containsBytesMap(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
return internalGetBytesMap().getMap().containsKey(key);
}
/**
* Use {@link #getBytesMapMap()} instead.
*/
@java.lang.Deprecated
public java.util.Map<java.lang.String, com.google.protobuf.ByteString> getBytesMap() {
return getBytesMapMap();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public java.util.Map<java.lang.String, com.google.protobuf.ByteString> getBytesMapMap() {
return internalGetBytesMap().getMap();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public com.google.protobuf.ByteString getBytesMapOrDefault(
java.lang.String key, com.google.protobuf.ByteString defaultValue) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, com.google.protobuf.ByteString> map =
internalGetBytesMap().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public com.google.protobuf.ByteString getBytesMapOrThrow(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, com.google.protobuf.ByteString> map =
internalGetBytesMap().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public Builder clearBytesMap() {
internalGetMutableBytesMap().getMutableMap().clear();
return this;
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public Builder removeBytesMap(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
internalGetMutableBytesMap().getMutableMap().remove(key);
return this;
}
/**
* Use alternate mutation accessors instead.
*/
@java.lang.Deprecated
public java.util.Map<java.lang.String, com.google.protobuf.ByteString> getMutableBytesMap() {
return internalGetMutableBytesMap().getMutableMap();
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public Builder putBytesMap(java.lang.String key, com.google.protobuf.ByteString value) {
if (key == null) {
throw new java.lang.NullPointerException();
}
if (value == null) {
throw new java.lang.NullPointerException();
}
internalGetMutableBytesMap().getMutableMap().put(key, value);
return this;
}
/**
* <code>map<string, bytes> bytesMap = 11;</code>
*/
public Builder putAllBytesMap(java.util.Map<java.lang.String, com.google.protobuf.ByteString> values) {
internalGetMutableBytesMap().getMutableMap().putAll(values);
return this;
}
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType)
}
// @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType)
private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType();
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated
public static final com.google.protobuf.Parser<PBRequestType> PARSER =
new com.google.protobuf.AbstractParser<PBRequestType>() {
public PBRequestType parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PBRequestType(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PBRequestType> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PBRequestType> getParserForType() {
return PARSER;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface PBResponseTypeOrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional string msg = 1;</code>
*/
boolean hasMsg();
/**
* <code>optional string msg = 1;</code>
*/
java.lang.String getMsg();
/**
* <code>optional string msg = 1;</code>
*/
com.google.protobuf.ByteString getMsgBytes();
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
boolean hasCDubboPBRequestType();
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType();
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder
getCDubboPBRequestTypeOrBuilder();
}
/**
* Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType}
*/
public static final class PBResponseType extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType)
PBResponseTypeOrBuilder {
private static final long serialVersionUID = 0L;
// Use PBResponseType.newBuilder() to construct.
private PBResponseType(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PBResponseType() {
msg_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private PBResponseType(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
msg_ = bs;
break;
}
case 26: {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder
subBuilder = null;
if (((bitField0_ & 0x00000002) == 0x00000002)) {
subBuilder = cDubboPBRequestType_.toBuilder();
}
cDubboPBRequestType_ = input.readMessage(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.PARSER,
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(cDubboPBRequestType_);
cDubboPBRequestType_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000002;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor;
}
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.class,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.Builder.class);
}
private int bitField0_;
public static final int MSG_FIELD_NUMBER = 1;
private volatile java.lang.Object msg_;
/**
* <code>optional string msg = 1;</code>
*/
public boolean hasMsg() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string msg = 1;</code>
*/
public java.lang.String getMsg() {
java.lang.Object ref = msg_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
msg_ = s;
}
return s;
}
}
/**
* <code>optional string msg = 1;</code>
*/
public com.google.protobuf.ByteString getMsgBytes() {
java.lang.Object ref = msg_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
msg_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CDUBBOPBREQUESTTYPE_FIELD_NUMBER = 3;
private org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType cDubboPBRequestType_;
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public boolean hasCDubboPBRequestType() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType() {
return cDubboPBRequestType_ == null
? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance()
: cDubboPBRequestType_;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder
getCDubboPBRequestTypeOrBuilder() {
return cDubboPBRequestType_ == null
? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.getDefaultInstance()
: cDubboPBRequestType_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (hasCDubboPBRequestType()) {
if (!getCDubboPBRequestType().isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, msg_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeMessage(3, getCDubboPBRequestType());
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, msg_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCDubboPBRequestType());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType)) {
return super.equals(obj);
}
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType other =
(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) obj;
boolean result = true;
result = result && (hasMsg() == other.hasMsg());
if (hasMsg()) {
result = result && getMsg().equals(other.getMsg());
}
result = result && (hasCDubboPBRequestType() == other.hasCDubboPBRequestType());
if (hasCDubboPBRequestType()) {
result = result && getCDubboPBRequestType().equals(other.getCDubboPBRequestType());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasMsg()) {
hash = (37 * hash) + MSG_FIELD_NUMBER;
hash = (53 * hash) + getMsg().hashCode();
}
if (hasCDubboPBRequestType()) {
hash = (37 * hash) + CDUBBOPBREQUESTTYPE_FIELD_NUMBER;
hash = (53 * hash) + getCDubboPBRequestType().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType)
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseTypeOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor;
}
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.class,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.Builder
.class);
}
// Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getCDubboPBRequestTypeFieldBuilder();
}
}
public Builder clear() {
super.clear();
msg_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
if (cDubboPBRequestTypeBuilder_ == null) {
cDubboPBRequestType_ = null;
} else {
cDubboPBRequestTypeBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType
getDefaultInstanceForType() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType.getDefaultInstance();
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType build() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType buildPartial() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType result =
new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.msg_ = msg_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
if (cDubboPBRequestTypeBuilder_ == null) {
result.cDubboPBRequestType_ = cDubboPBRequestType_;
} else {
result.cDubboPBRequestType_ = cDubboPBRequestTypeBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) {
return mergeFrom(
(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType other) {
if (other
== org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType
.getDefaultInstance()) return this;
if (other.hasMsg()) {
bitField0_ |= 0x00000001;
msg_ = other.msg_;
onChanged();
}
if (other.hasCDubboPBRequestType()) {
mergeCDubboPBRequestType(other.getCDubboPBRequestType());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
if (hasCDubboPBRequestType()) {
if (!getCDubboPBRequestType().isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object msg_ = "";
/**
* <code>optional string msg = 1;</code>
*/
public boolean hasMsg() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string msg = 1;</code>
*/
public java.lang.String getMsg() {
java.lang.Object ref = msg_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
msg_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string msg = 1;</code>
*/
public com.google.protobuf.ByteString getMsgBytes() {
java.lang.Object ref = msg_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
msg_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string msg = 1;</code>
*/
public Builder setMsg(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
msg_ = value;
onChanged();
return this;
}
/**
* <code>optional string msg = 1;</code>
*/
public Builder clearMsg() {
bitField0_ = (bitField0_ & ~0x00000001);
msg_ = getDefaultInstance().getMsg();
onChanged();
return this;
}
/**
* <code>optional string msg = 1;</code>
*/
public Builder setMsgBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
msg_ = value;
onChanged();
return this;
}
private org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType cDubboPBRequestType_ =
null;
private com.google.protobuf.SingleFieldBuilderV3<
PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder>
cDubboPBRequestTypeBuilder_;
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public boolean hasCDubboPBRequestType() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType getCDubboPBRequestType() {
if (cDubboPBRequestTypeBuilder_ == null) {
return cDubboPBRequestType_ == null
? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType
.getDefaultInstance()
: cDubboPBRequestType_;
} else {
return cDubboPBRequestTypeBuilder_.getMessage();
}
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public Builder setCDubboPBRequestType(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType value) {
if (cDubboPBRequestTypeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
cDubboPBRequestType_ = value;
onChanged();
} else {
cDubboPBRequestTypeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
return this;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public Builder setCDubboPBRequestType(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder
builderForValue) {
if (cDubboPBRequestTypeBuilder_ == null) {
cDubboPBRequestType_ = builderForValue.build();
onChanged();
} else {
cDubboPBRequestTypeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
return this;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public Builder mergeCDubboPBRequestType(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType value) {
if (cDubboPBRequestTypeBuilder_ == null) {
if (((bitField0_ & 0x00000002) == 0x00000002)
&& cDubboPBRequestType_ != null
&& cDubboPBRequestType_
!= org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType
.getDefaultInstance()) {
cDubboPBRequestType_ =
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.newBuilder(
cDubboPBRequestType_)
.mergeFrom(value)
.buildPartial();
} else {
cDubboPBRequestType_ = value;
}
onChanged();
} else {
cDubboPBRequestTypeBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000002;
return this;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public Builder clearCDubboPBRequestType() {
if (cDubboPBRequestTypeBuilder_ == null) {
cDubboPBRequestType_ = null;
onChanged();
} else {
cDubboPBRequestTypeBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType.Builder
getCDubboPBRequestTypeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getCDubboPBRequestTypeFieldBuilder().getBuilder();
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestTypeOrBuilder
getCDubboPBRequestTypeOrBuilder() {
if (cDubboPBRequestTypeBuilder_ != null) {
return cDubboPBRequestTypeBuilder_.getMessageOrBuilder();
} else {
return cDubboPBRequestType_ == null
? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBRequestType
.getDefaultInstance()
: cDubboPBRequestType_;
}
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PBRequestType CDubboPBRequestType = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder>
getCDubboPBRequestTypeFieldBuilder() {
if (cDubboPBRequestTypeBuilder_ == null) {
cDubboPBRequestTypeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
PBRequestType, PBRequestType.Builder, PBRequestTypeOrBuilder>(
getCDubboPBRequestType(), getParentForChildren(), isClean());
cDubboPBRequestType_ = null;
}
return cDubboPBRequestTypeBuilder_;
}
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType)
}
// @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PBResponseType)
private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType();
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated
public static final com.google.protobuf.Parser<PBResponseType> PARSER =
new com.google.protobuf.AbstractParser<PBResponseType>() {
public PBResponseType parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PBResponseType(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PBResponseType> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PBResponseType> getParserForType() {
return PARSER;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PBResponseType getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface PhoneNumberOrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber)
com.google.protobuf.MessageOrBuilder {
/**
* <code>required string number = 1;</code>
*/
boolean hasNumber();
/**
* <code>required string number = 1;</code>
*/
java.lang.String getNumber();
/**
* <code>required string number = 1;</code>
*/
com.google.protobuf.ByteString getNumberBytes();
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
boolean hasType();
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType();
}
/**
* Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber}
*/
public static final class PhoneNumber extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber)
PhoneNumberOrBuilder {
private static final long serialVersionUID = 0L;
// Use PhoneNumber.newBuilder() to construct.
private PhoneNumber(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PhoneNumber() {
number_ = "";
type_ = 1;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private PhoneNumber(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
number_ = bs;
break;
}
case 16: {
int rawValue = input.readEnum();
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType value =
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(
rawValue);
if (value == null) {
unknownFields.mergeVarintField(2, rawValue);
} else {
bitField0_ |= 0x00000002;
type_ = rawValue;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor;
}
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.class,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder.class);
}
private int bitField0_;
public static final int NUMBER_FIELD_NUMBER = 1;
private volatile java.lang.Object number_;
/**
* <code>required string number = 1;</code>
*/
public boolean hasNumber() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string number = 1;</code>
*/
public java.lang.String getNumber() {
java.lang.Object ref = number_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
number_ = s;
}
return s;
}
}
/**
* <code>required string number = 1;</code>
*/
public com.google.protobuf.ByteString getNumberBytes() {
java.lang.Object ref = number_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
number_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TYPE_FIELD_NUMBER = 2;
private int type_;
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
public boolean hasType() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType result =
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(type_);
return result == null
? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.HOME
: result;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasNumber()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, number_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeEnum(2, type_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, number_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, type_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber)) {
return super.equals(obj);
}
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber other =
(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) obj;
boolean result = true;
result = result && (hasNumber() == other.hasNumber());
if (hasNumber()) {
result = result && getNumber().equals(other.getNumber());
}
result = result && (hasType() == other.hasType());
if (hasType()) {
result = result && type_ == other.type_;
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasNumber()) {
hash = (37 * hash) + NUMBER_FIELD_NUMBER;
hash = (53 * hash) + getNumber().hashCode();
}
if (hasType()) {
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + type_;
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber)
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumberOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor;
}
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.class,
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.Builder.class);
}
// Construct using org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
public Builder clear() {
super.clear();
number_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
type_ = 1;
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB
.internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber
getDefaultInstanceForType() {
return org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber.getDefaultInstance();
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber build() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber buildPartial() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber result =
new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.number_ = number_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.type_ = type_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) {
return mergeFrom((org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber other) {
if (other
== org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber
.getDefaultInstance()) return this;
if (other.hasNumber()) {
bitField0_ |= 0x00000001;
number_ = other.number_;
onChanged();
}
if (other.hasType()) {
setType(other.getType());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
if (!hasNumber()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object number_ = "";
/**
* <code>required string number = 1;</code>
*/
public boolean hasNumber() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string number = 1;</code>
*/
public java.lang.String getNumber() {
java.lang.Object ref = number_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
number_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string number = 1;</code>
*/
public com.google.protobuf.ByteString getNumberBytes() {
java.lang.Object ref = number_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
number_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string number = 1;</code>
*/
public Builder setNumber(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
number_ = value;
onChanged();
return this;
}
/**
* <code>required string number = 1;</code>
*/
public Builder clearNumber() {
bitField0_ = (bitField0_ & ~0x00000001);
number_ = getDefaultInstance().getNumber();
onChanged();
return this;
}
/**
* <code>required string number = 1;</code>
*/
public Builder setNumberBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
number_ = value;
onChanged();
return this;
}
private int type_ = 1;
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
public boolean hasType() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType getType() {
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType result =
org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.valueOf(type_);
return result == null
? org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType.HOME
: result;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
public Builder setType(org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
type_ = value.getNumber();
onChanged();
return this;
}
/**
* <code>optional .org.apache.dubbo.metadata.definition.protobuf.model.PhoneType type = 2 [default = HOME];</code>
*/
public Builder clearType() {
bitField0_ = (bitField0_ & ~0x00000002);
type_ = 1;
onChanged();
return this;
}
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber)
}
// @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.definition.protobuf.model.PhoneNumber)
private static final org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber();
}
public static org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated
public static final com.google.protobuf.Parser<PhoneNumber> PARSER =
new com.google.protobuf.AbstractParser<PhoneNumber>() {
public PhoneNumber parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PhoneNumber(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PhoneNumber> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PhoneNumber> getParserForType() {
return PARSER;
}
public org.apache.dubbo.metadata.definition.protobuf.model.GooglePB.PhoneNumber getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor;
private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor;
private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor;
private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor;
private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor;
private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n\016GooglePB.proto\0223org.apache.dubbo.metad" + "ata.definition.protobuf.model\"\301\004\n\rPBRequ"
+ "estType\022\r\n\005money\030\001 \001(\001\022\014\n\004cash\030\002 \001(\002\022\013\n\003"
+ "age\030\003 \001(\005\022\013\n\003num\030\004 \001(\003\022\013\n\003sex\030\005 \001(\010\022\014\n\004n"
+ "ame\030\006 \001(\t\022\013\n\003msg\030\007 \001(\014\022O\n\005phone\030\010 \003(\0132@."
+ "org.apache.dubbo.metadata.definition.pro"
+ "tobuf.model.PhoneNumber\022d\n\tdoubleMap\030\t \003"
+ "(\0132Q.org.apache.dubbo.metadata.definitio"
+ "n.protobuf.model.PBRequestType.DoubleMap"
+ "Entry\022\021\n\tbytesList\030\n \003(\014\022b\n\010bytesMap\030\013 \003",
"(\0132P.org.apache.dubbo.metadata.definitio" + "n.protobuf.model.PBRequestType.BytesMapE"
+ "ntry\032r\n\016DoubleMapEntry\022\013\n\003key\030\001 \001(\t\022O\n\005v"
+ "alue\030\002 \001(\[email protected]"
+ "efinition.protobuf.model.PhoneNumber:\0028\001"
+ "\032/\n\rBytesMapEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030"
+ "\002 \001(\014:\0028\001\"~\n\016PBResponseType\022\013\n\003msg\030\001 \001(\t"
+ "\022_\n\023CDubboPBRequestType\030\003 \001(\0132B.org.apac"
+ "he.dubbo.metadata.definition.protobuf.mo"
+ "del.PBRequestType\"q\n\013PhoneNumber\022\016\n\006numb",
"er\030\001 \002(\t\022R\n\004type\030\002 \001(\0162>.org.apache.dubb"
+ "o.metadata.definition.protobuf.model.Pho"
+ "neType:\004HOME*+\n\tPhoneType\022\n\n\006MOBILE\020\000\022\010\n"
+ "\004HOME\020\001\022\010\n\004WORK\020\0022\247\001\n\017CDubboPBService\022\223\001"
+ "\n\010sayHello\022B.org.apache.dubbo.metadata.d"
+ "efinition.protobuf.model.PBRequestType\032C"
+ ".org.apache.dubbo.metadata.definition.pr"
+ "otobuf.model.PBResponseType"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor,
new java.lang.String[] {
"Money",
"Cash",
"Age",
"Num",
"Sex",
"Name",
"Msg",
"Phone",
"DoubleMap",
"BytesList",
"BytesMap",
});
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor =
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor
.getNestedTypes()
.get(0);
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_DoubleMapEntry_descriptor,
new java.lang.String[] {
"Key", "Value",
});
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor =
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_descriptor
.getNestedTypes()
.get(1);
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBRequestType_BytesMapEntry_descriptor,
new java.lang.String[] {
"Key", "Value",
});
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PBResponseType_descriptor,
new java.lang.String[] {
"Msg", "CDubboPBRequestType",
});
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_definition_protobuf_model_PhoneNumber_descriptor,
new java.lang.String[] {
"Number", "Type",
});
}
// @@protoc_insertion_point(outer_class_scope)
}
| 7,304 |
0 |
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition
|
Create_ds/dubbo/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.definition.protobuf;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.metadata.definition.TypeDefinitionBuilder;
import org.apache.dubbo.metadata.definition.builder.TypeBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.ProtocolStringList;
import com.google.protobuf.UnknownFieldSet;
@Activate(onClass = "com.google.protobuf.GeneratedMessageV3")
public class ProtobufTypeBuilder implements TypeBuilder, Prioritized {
private final Logger logger = LoggerFactory.getLogger(getClass());
private static final Pattern MAP_PATTERN = Pattern.compile("^java\\.util\\.Map<(\\S+), (\\S+)>$");
private static final Pattern LIST_PATTERN = Pattern.compile("^java\\.util\\.List<(\\S+)>$");
private static final List<String> LIST = null;
/**
* provide a List<String> type for TypeDefinitionBuilder.build(type,class,cache)
* "repeated string" transform to ProtocolStringList, should be build as List<String> type.
*/
private static Type STRING_LIST_TYPE;
private final boolean protobufExist;
static {
try {
STRING_LIST_TYPE =
ProtobufTypeBuilder.class.getDeclaredField("LIST").getGenericType();
} catch (NoSuchFieldException e) {
// do nothing
}
}
public ProtobufTypeBuilder() {
protobufExist = checkProtobufExist();
}
private boolean checkProtobufExist() {
try {
Class.forName("com.google.protobuf.GeneratedMessageV3");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
@Override
public int getPriority() {
return -1;
}
@Override
public boolean accept(Class<?> clazz) {
if (clazz == null) {
return false;
}
if (!protobufExist) {
return false;
}
return GeneratedMessageV3.class.isAssignableFrom(clazz);
}
@Override
public TypeDefinition build(Type type, Class<?> clazz, Map<String, TypeDefinition> typeCache) {
String canonicalName = clazz.getCanonicalName();
TypeDefinition typeDefinition = typeCache.get(canonicalName);
if (typeDefinition != null) {
return typeDefinition;
}
try {
GeneratedMessageV3.Builder builder = getMessageBuilder(clazz);
typeDefinition = buildProtobufTypeDefinition(clazz, builder, typeCache);
typeCache.put(canonicalName, typeDefinition);
} catch (Exception e) {
logger.info("TypeDefinition build failed.", e);
}
return typeDefinition;
}
private GeneratedMessageV3.Builder getMessageBuilder(Class<?> requestType) throws Exception {
Method method = requestType.getMethod("newBuilder");
return (GeneratedMessageV3.Builder) method.invoke(null, null);
}
private TypeDefinition buildProtobufTypeDefinition(
Class<?> clazz, GeneratedMessageV3.Builder builder, Map<String, TypeDefinition> typeCache) {
String canonicalName = clazz.getCanonicalName();
TypeDefinition td = new TypeDefinition(canonicalName);
if (builder == null) {
return td;
}
Map<String, String> properties = new HashMap<>();
Method[] methods = builder.getClass().getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
if (isSimplePropertySettingMethod(method)) {
// property of custom type or primitive type
TypeDefinition fieldTd = TypeDefinitionBuilder.build(
method.getGenericParameterTypes()[0], method.getParameterTypes()[0], typeCache);
properties.put(generateSimpleFiledName(methodName), fieldTd.getType());
} else if (isMapPropertySettingMethod(method)) {
// property of map
Type type = method.getGenericParameterTypes()[0];
String fieldName = generateMapFieldName(methodName);
validateMapType(fieldName, type.toString());
TypeDefinition fieldTd = TypeDefinitionBuilder.build(type, method.getParameterTypes()[0], typeCache);
properties.put(fieldName, fieldTd.getType());
} else if (isListPropertyGettingMethod(method)) {
// property of list
Type type = method.getGenericReturnType();
String fieldName = generateListFieldName(methodName);
TypeDefinition fieldTd;
if (ProtocolStringList.class.isAssignableFrom(method.getReturnType())) {
// property defined as "repeated string" transform to ProtocolStringList,
// should be build as List<String>.
fieldTd = TypeDefinitionBuilder.build(STRING_LIST_TYPE, List.class, typeCache);
} else {
// property without generic type should not be build ex method return List
if (!LIST_PATTERN.matcher(type.toString()).matches()) {
continue;
}
fieldTd = TypeDefinitionBuilder.build(type, method.getReturnType(), typeCache);
}
properties.put(fieldName, fieldTd.getType());
}
}
td.setProperties(properties);
return td;
}
/**
* 1. Unsupported Map with key type is not String <br/>
* Bytes is a primitive type in Proto, transform to ByteString.class in java<br/>
*
* @param fieldName
* @param typeName
* @return
*/
private void validateMapType(String fieldName, String typeName) {
Matcher matcher = MAP_PATTERN.matcher(typeName);
if (!matcher.matches()) {
throw new IllegalArgumentException("Map protobuf property " + fieldName + "of Type " + typeName
+ " can't be parsed.The type name should mathch[" + MAP_PATTERN.toString() + "].");
}
}
/**
* get unCollection unMap property name from setting method.<br/>
* ex:setXXX();<br/>
*
* @param methodName
* @return
*/
private String generateSimpleFiledName(String methodName) {
return toCamelCase(methodName.substring(3));
}
/**
* get map property name from setting method.<br/>
* ex: putAllXXX();<br/>
*
* @param methodName
* @return
*/
private String generateMapFieldName(String methodName) {
return toCamelCase(methodName.substring(6));
}
/**
* get list property name from setting method.<br/>
* ex: getXXXList()<br/>
*
* @param methodName
* @return
*/
private String generateListFieldName(String methodName) {
return toCamelCase(methodName.substring(3, methodName.length() - 4));
}
private String toCamelCase(String nameString) {
char[] chars = nameString.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
/**
* judge custom type or primitive type property<br/>
* 1. proto3 grammar ex: string name = 1 <br/>
* 2. proto3 grammar ex: optional string name =1 <br/>
* generated setting method ex: setNameValue(String name);
*
* @param method
* @return
*/
private boolean isSimplePropertySettingMethod(Method method) {
String methodName = method.getName();
Class<?>[] types = method.getParameterTypes();
if (!methodName.startsWith("set") || types.length != 1) {
return false;
}
// filter general setting method
// 1. - setUnknownFields( com.google.protobuf.UnknownFieldSet unknownFields)
// 2. - setField(com.google.protobuf.Descriptors.FieldDescriptor field,java.lang.Object value)
// 3. - setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index,java.lang.Object value)
if ("setField".equals(methodName) && types[0].equals(Descriptors.FieldDescriptor.class)
|| "setUnknownFields".equals(methodName) && types[0].equals(UnknownFieldSet.class)
|| "setRepeatedField".equals(methodName) && types[0].equals(Descriptors.FieldDescriptor.class)) {
return false;
}
// String property has two setting method.
// skip setXXXBytes(com.google.protobuf.ByteString value)
// parse setXXX(String string)
if (methodName.endsWith("Bytes") && types[0].equals(ByteString.class)) {
return false;
}
// Protobuf property has two setting method.
// skip setXXX(com.google.protobuf.Builder value)
// parse setXXX(com.google.protobuf.Message value)
if (GeneratedMessageV3.Builder.class.isAssignableFrom(types[0])) {
return false;
}
// Enum property has two setting method.
// skip setXXXValue(int value)
// parse setXXX(SomeEnum value)
return !methodName.endsWith("Value") || types[0] != int.class;
}
/**
* judge List property</br>
* proto3 grammar ex: repeated string names; </br>
* generated getting method:List<String> getNamesList()
*
* @param method
* @return
*/
boolean isListPropertyGettingMethod(Method method) {
String methodName = method.getName();
Class<?> type = method.getReturnType();
if (!methodName.startsWith("get") || !methodName.endsWith("List")) {
return false;
}
// skip the setting method with Pb entity builder as parameter
if (methodName.endsWith("BuilderList")) {
return false;
}
// if field name end with List, should skip
return List.class.isAssignableFrom(type);
}
/**
* judge map property</br>
* proto3 grammar : map<string,string> card = 1; </br>
* generated setting method: putAllCards(java.util.Map<String, string> values) </br>
*
* @param methodTemp
* @return
*/
private boolean isMapPropertySettingMethod(Method methodTemp) {
String methodName = methodTemp.getName();
Class[] parameters = methodTemp.getParameterTypes();
return methodName.startsWith("putAll") && parameters.length == 1 && Map.class.isAssignableFrom(parameters[0]);
}
}
| 7,305 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/AbstractGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.base.Strings;
import com.google.common.html.HtmlEscapers;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileOptions;
import com.google.protobuf.DescriptorProtos.MethodDescriptorProto;
import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;
import com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location;
import com.google.protobuf.compiler.PluginProtos;
import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse.Feature;
import com.salesforce.jprotoc.Generator;
import com.salesforce.jprotoc.GeneratorException;
import com.salesforce.jprotoc.ProtoTypeMap;
public abstract class AbstractGenerator extends Generator {
private static final int SERVICE_NUMBER_OF_PATHS = 2;
private static final int METHOD_NUMBER_OF_PATHS = 4;
protected abstract String getClassPrefix();
protected abstract String getClassSuffix();
protected String getSingleTemplateFileName() {
return getTemplateFileName();
}
protected String getTemplateFileName() {
return getClassPrefix() + getClassSuffix() + "Stub.mustache";
}
protected String getInterfaceTemplateFileName() {
return getClassPrefix() + getClassSuffix() + "InterfaceStub.mustache";
}
@Override
protected List<Feature> supportedFeatures() {
return Collections.singletonList(Feature.FEATURE_PROTO3_OPTIONAL);
}
private String getServiceJavaDocPrefix() {
return " ";
}
private String getMethodJavaDocPrefix() {
return " ";
}
@Override
public List<PluginProtos.CodeGeneratorResponse.File> generateFiles(PluginProtos.CodeGeneratorRequest request)
throws GeneratorException {
final ProtoTypeMap typeMap = ProtoTypeMap.of(request.getProtoFileList());
List<FileDescriptorProto> protosToGenerate = request.getProtoFileList().stream()
.filter(protoFile -> request.getFileToGenerateList().contains(protoFile.getName()))
.collect(Collectors.toList());
List<ServiceContext> services = findServices(protosToGenerate, typeMap);
return generateFiles(services);
}
private List<ServiceContext> findServices(List<FileDescriptorProto> protos, ProtoTypeMap typeMap) {
List<ServiceContext> contexts = new ArrayList<>();
protos.forEach(fileProto -> {
for (int serviceNumber = 0; serviceNumber < fileProto.getServiceCount(); serviceNumber++) {
ServiceContext serviceContext = buildServiceContext(
fileProto.getService(serviceNumber),
typeMap,
fileProto.getSourceCodeInfo().getLocationList(),
serviceNumber);
serviceContext.protoName = fileProto.getName();
serviceContext.packageName = extractPackageName(fileProto);
if (!Strings.isNullOrEmpty(fileProto.getOptions().getJavaOuterClassname())) {
serviceContext.outerClassName = fileProto.getOptions().getJavaOuterClassname();
}
serviceContext.commonPackageName = extractCommonPackageName(fileProto);
serviceContext.multipleFiles = fileProto.getOptions().getJavaMultipleFiles();
contexts.add(serviceContext);
}
});
return contexts;
}
private String extractPackageName(FileDescriptorProto proto) {
FileOptions options = proto.getOptions();
String javaPackage = options.getJavaPackage();
if (!Strings.isNullOrEmpty(javaPackage)) {
return javaPackage;
}
return Strings.nullToEmpty(proto.getPackage());
}
private String extractCommonPackageName(FileDescriptorProto proto) {
return Strings.nullToEmpty(proto.getPackage());
}
private ServiceContext buildServiceContext(
ServiceDescriptorProto serviceProto, ProtoTypeMap typeMap, List<Location> locations, int serviceNumber) {
ServiceContext serviceContext = new ServiceContext();
serviceContext.fileName = getClassPrefix() + serviceProto.getName() + getClassSuffix() + ".java";
serviceContext.className = getClassPrefix() + serviceProto.getName() + getClassSuffix();
serviceContext.outerClassName = serviceProto.getName() + "OuterClass";
serviceContext.interfaceFileName = serviceProto.getName() + ".java";
serviceContext.interfaceClassName = serviceProto.getName();
serviceContext.serviceName = serviceProto.getName();
serviceContext.deprecated = serviceProto.getOptions().getDeprecated();
List<Location> allLocationsForService = locations.stream()
.filter(location -> location.getPathCount() >= 2
&& location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER
&& location.getPath(1) == serviceNumber)
.collect(Collectors.toList());
Location serviceLocation = allLocationsForService.stream()
.filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS)
.findFirst()
.orElseGet(Location::getDefaultInstance);
serviceContext.javaDoc = getJavaDoc(getComments(serviceLocation), getServiceJavaDocPrefix());
for (int methodNumber = 0; methodNumber < serviceProto.getMethodCount(); methodNumber++) {
MethodContext methodContext =
buildMethodContext(serviceProto.getMethod(methodNumber), typeMap, locations, methodNumber);
serviceContext.methods.add(methodContext);
serviceContext.methodTypes.add(methodContext.inputType);
serviceContext.methodTypes.add(methodContext.outputType);
}
return serviceContext;
}
private MethodContext buildMethodContext(
MethodDescriptorProto methodProto, ProtoTypeMap typeMap, List<Location> locations, int methodNumber) {
MethodContext methodContext = new MethodContext();
methodContext.originMethodName = methodProto.getName();
methodContext.methodName = lowerCaseFirst(methodProto.getName());
methodContext.inputType = typeMap.toJavaTypeName(methodProto.getInputType());
methodContext.outputType = typeMap.toJavaTypeName(methodProto.getOutputType());
methodContext.deprecated = methodProto.getOptions().getDeprecated();
methodContext.isManyInput = methodProto.getClientStreaming();
methodContext.isManyOutput = methodProto.getServerStreaming();
methodContext.methodNumber = methodNumber;
Location methodLocation = locations.stream()
.filter(location -> location.getPathCount() == METHOD_NUMBER_OF_PATHS
&& location.getPath(METHOD_NUMBER_OF_PATHS - 1) == methodNumber)
.findFirst()
.orElseGet(Location::getDefaultInstance);
methodContext.javaDoc = getJavaDoc(getComments(methodLocation), getMethodJavaDocPrefix());
if (!methodProto.getClientStreaming() && !methodProto.getServerStreaming()) {
methodContext.reactiveCallsMethodName = "oneToOne";
methodContext.grpcCallsMethodName = "asyncUnaryCall";
}
if (!methodProto.getClientStreaming() && methodProto.getServerStreaming()) {
methodContext.reactiveCallsMethodName = "oneToMany";
methodContext.grpcCallsMethodName = "asyncServerStreamingCall";
}
if (methodProto.getClientStreaming() && !methodProto.getServerStreaming()) {
methodContext.reactiveCallsMethodName = "manyToOne";
methodContext.grpcCallsMethodName = "asyncClientStreamingCall";
}
if (methodProto.getClientStreaming() && methodProto.getServerStreaming()) {
methodContext.reactiveCallsMethodName = "manyToMany";
methodContext.grpcCallsMethodName = "asyncBidiStreamingCall";
}
return methodContext;
}
private String lowerCaseFirst(String s) {
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
private List<PluginProtos.CodeGeneratorResponse.File> generateFiles(List<ServiceContext> services) {
List<PluginProtos.CodeGeneratorResponse.File> allServiceFiles = new ArrayList<>();
for (ServiceContext context : services) {
List<PluginProtos.CodeGeneratorResponse.File> files = buildFile(context);
allServiceFiles.addAll(files);
}
return allServiceFiles;
}
protected boolean enableMultipleTemplateFiles() {
return false;
}
private List<PluginProtos.CodeGeneratorResponse.File> buildFile(ServiceContext context) {
List<PluginProtos.CodeGeneratorResponse.File> files = new ArrayList<>();
if (context.multipleFiles && enableMultipleTemplateFiles()) {
String content = applyTemplate(getTemplateFileName(), context);
String dir = absoluteDir(context);
files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder()
.setName(getFileName(dir, context.fileName))
.setContent(content)
.build());
content = applyTemplate(getInterfaceTemplateFileName(), context);
files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder()
.setName(getFileName(dir, context.interfaceFileName))
.setContent(content)
.build());
} else {
String content = applyTemplate(getSingleTemplateFileName(), context);
String dir = absoluteDir(context);
files.add(PluginProtos.CodeGeneratorResponse.File.newBuilder()
.setName(getFileName(dir, context.fileName))
.setContent(content)
.build());
}
return files;
}
private String absoluteDir(ServiceContext ctx) {
return ctx.packageName.replace('.', '/');
}
private String getFileName(String dir, String fileName) {
if (Strings.isNullOrEmpty(dir)) {
return fileName;
}
return dir + "/" + fileName;
}
private String getComments(Location location) {
return location.getLeadingComments().isEmpty() ? location.getTrailingComments() : location.getLeadingComments();
}
private String getJavaDoc(String comments, String prefix) {
if (!comments.isEmpty()) {
StringBuilder builder = new StringBuilder("/**\n").append(prefix).append(" * <pre>\n");
Arrays.stream(HtmlEscapers.htmlEscaper().escape(comments).split("\n"))
.map(line -> line.replace("*/", "*/").replace("*", "*"))
.forEach(line ->
builder.append(prefix).append(" * ").append(line).append("\n"));
builder.append(prefix).append(" * </pre>\n").append(prefix).append(" */");
return builder.toString();
}
return null;
}
/**
* Template class for proto Service objects.
*/
private class ServiceContext {
// CHECKSTYLE DISABLE VisibilityModifier FOR 8 LINES
public String fileName;
public String interfaceFileName;
public String protoName;
public String packageName;
public String commonPackageName;
public String className;
public String interfaceClassName;
public String serviceName;
public boolean deprecated;
public String javaDoc;
public boolean multipleFiles;
public String outerClassName;
public List<MethodContext> methods = new ArrayList<>();
public Set<String> methodTypes = new HashSet<>();
public List<MethodContext> unaryRequestMethods() {
return methods.stream().filter(m -> !m.isManyInput).collect(Collectors.toList());
}
public List<MethodContext> unaryMethods() {
return methods.stream()
.filter(m -> (!m.isManyInput && !m.isManyOutput))
.collect(Collectors.toList());
}
public List<MethodContext> serverStreamingMethods() {
return methods.stream()
.filter(m -> !m.isManyInput && m.isManyOutput)
.collect(Collectors.toList());
}
public List<MethodContext> biStreamingMethods() {
return methods.stream().filter(m -> m.isManyInput).collect(Collectors.toList());
}
public List<MethodContext> biStreamingWithoutClientStreamMethods() {
return methods.stream().filter(m -> m.isManyInput && m.isManyOutput).collect(Collectors.toList());
}
public List<MethodContext> clientStreamingMethods() {
return methods.stream()
.filter(m -> m.isManyInput && !m.isManyOutput)
.collect(Collectors.toList());
}
public List<MethodContext> methods() {
return methods;
}
}
/**
* Template class for proto RPC objects.
*/
private static class MethodContext {
// CHECKSTYLE DISABLE VisibilityModifier FOR 10 LINES
public String originMethodName;
public String methodName;
public String inputType;
public String outputType;
public boolean deprecated;
public boolean isManyInput;
public boolean isManyOutput;
public String reactiveCallsMethodName;
public String grpcCallsMethodName;
public int methodNumber;
public String javaDoc;
// This method mimics the upper-casing method ogf gRPC to ensure compatibility
// See https://github.com/grpc/grpc-java/blob/v1.8.0/compiler/src/java_plugin/cpp/java_generator.cpp#L58
public String methodNameUpperUnderscore() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < methodName.length(); i++) {
char c = methodName.charAt(i);
s.append(Character.toUpperCase(c));
if ((i < methodName.length() - 1)
&& Character.isLowerCase(c)
&& Character.isUpperCase(methodName.charAt(i + 1))) {
s.append('_');
}
}
return s.toString();
}
public String methodNamePascalCase() {
String mn = methodName.replace("_", "");
return String.valueOf(Character.toUpperCase(mn.charAt(0))) + mn.substring(1);
}
public String methodNameCamelCase() {
String mn = methodName.replace("_", "");
return String.valueOf(Character.toLowerCase(mn.charAt(0))) + mn.substring(1);
}
}
}
| 7,306 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/Dubbo3TripleGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.tri;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class Dubbo3TripleGenerator extends AbstractGenerator {
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new Dubbo3TripleGenerator());
} else {
ProtocPlugin.debug(new Dubbo3TripleGenerator(), args[0]);
}
}
@Override
protected String getClassPrefix() {
return "Dubbo";
}
@Override
protected String getClassSuffix() {
return "Triple";
}
@Override
protected String getTemplateFileName() {
return "Dubbo3TripleStub.mustache";
}
@Override
protected String getInterfaceTemplateFileName() {
return "Dubbo3TripleInterfaceStub.mustache";
}
@Override
protected String getSingleTemplateFileName() {
throw new IllegalStateException("Do not support single template!");
}
@Override
protected boolean enableMultipleTemplateFiles() {
return true;
}
}
| 7,307 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/tri/reactive/ReactorDubbo3TripleGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.tri.reactive;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class ReactorDubbo3TripleGenerator extends AbstractGenerator {
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new ReactorDubbo3TripleGenerator());
} else {
ProtocPlugin.debug(new ReactorDubbo3TripleGenerator(), args[0]);
}
}
@Override
protected String getClassPrefix() {
return "Dubbo";
}
@Override
protected String getClassSuffix() {
return "Triple";
}
@Override
protected String getTemplateFileName() {
return "ReactorDubbo3TripleStub.mustache";
}
@Override
protected String getInterfaceTemplateFileName() {
return "ReactorDubbo3TripleInterfaceStub.mustache";
}
@Override
protected String getSingleTemplateFileName() {
throw new IllegalStateException("Do not support single template!");
}
@Override
protected boolean enableMultipleTemplateFiles() {
return true;
}
}
| 7,308 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/DubboGrpcGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.grpc;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class DubboGrpcGenerator extends AbstractGenerator {
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new DubboGrpcGenerator());
} else {
ProtocPlugin.debug(new DubboGrpcGenerator(), args[0]);
}
}
@Override
protected String getClassPrefix() {
return "Dubbo";
}
protected String getClassSuffix() {
return "Grpc";
}
}
| 7,309 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/reactive/ReactorDubboGrpcGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.grpc.reactive;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class ReactorDubboGrpcGenerator extends AbstractGenerator {
@Override
protected String getClassPrefix() {
return "ReactorDubbo";
}
@Override
protected String getClassSuffix() {
return "Grpc";
}
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new ReactorDubboGrpcGenerator());
} else {
ProtocPlugin.debug(new ReactorDubboGrpcGenerator(), args[0]);
}
}
}
| 7,310 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/grpc/reactive/RxDubboGrpcGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.grpc.reactive;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class RxDubboGrpcGenerator extends AbstractGenerator {
@Override
protected String getClassPrefix() {
return "RxDubbo";
}
@Override
protected String getClassSuffix() {
return "Grpc";
}
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new RxDubboGrpcGenerator());
} else {
ProtocPlugin.debug(new RxDubboGrpcGenerator(), args[0]);
}
}
}
| 7,311 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/DubboGenerator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.dubbo;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class DubboGenerator extends AbstractGenerator {
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new DubboGenerator());
} else {
ProtocPlugin.debug(new DubboGenerator(), args[0]);
}
}
@Override
protected String getClassPrefix() {
return "";
}
@Override
protected String getClassSuffix() {
return "Dubbo";
}
}
| 7,312 |
0 |
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen
|
Create_ds/dubbo/dubbo-compiler/src/main/java/org/apache/dubbo/gen/dubbo/Dubbo3Generator.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.gen.dubbo;
import org.apache.dubbo.gen.AbstractGenerator;
import com.salesforce.jprotoc.ProtocPlugin;
public class Dubbo3Generator extends AbstractGenerator {
public static void main(String[] args) {
if (args.length == 0) {
ProtocPlugin.generate(new Dubbo3Generator());
} else {
ProtocPlugin.debug(new Dubbo3Generator(), args[0]);
}
}
@Override
protected String getClassPrefix() {
return "";
}
@Override
protected String getClassSuffix() {
return "Dubbo";
}
@Override
protected String getTemplateFileName() {
return "Dubbo3Stub.mustache";
}
@Override
protected String getInterfaceTemplateFileName() {
return "Dubbo3InterfaceStub.mustache";
}
@Override
protected String getSingleTemplateFileName() {
return "DubboStub3Single.mustache";
}
@Override
protected boolean enableMultipleTemplateFiles() {
return true;
}
}
| 7,313 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/ErrorHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common;
@FunctionalInterface
public interface ErrorHandler {
/**
* Handle the given error, possibly rethrowing it as a fatal exception.
*/
void handleError(Throwable t);
}
| 7,314 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/SysProps.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Use to set and clear System property
*/
public class SysProps {
private static Map<String, String> map = new LinkedHashMap<String, String>();
public static void reset() {
map.clear();
}
public static void setProperty(String key, String value) {
map.put(key, value);
System.setProperty(key, value);
}
public static void clear() {
for (String key : map.keySet()) {
System.clearProperty(key);
}
reset();
}
}
| 7,315 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/RestDemoServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common.impl;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.test.common.api.RestDemoService;
import java.util.Map;
public class RestDemoServiceImpl implements RestDemoService {
private static Map<String, Object> context;
private boolean called;
public String sayHello(String name) {
called = true;
return "Hello, " + name;
}
public boolean isCalled() {
return called;
}
@Override
public Integer hello(Integer a, Integer b) {
context = RpcContext.getServerAttachment().getObjectAttachments();
return a + b;
}
@Override
public String error() {
throw new RuntimeException();
}
public static Map<String, Object> getAttachments() {
return context;
}
@Override
public String getRemoteApplicationName() {
return RpcContext.getServiceContext().getRemoteApplicationName();
}
}
| 7,316 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/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.test.common.impl;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.test.common.api.DemoService;
import java.util.concurrent.CompletableFuture;
@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
@Override
public CompletableFuture<String> sayHelloAsync(String name) {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
return "async result:" + name;
});
return cf;
}
}
| 7,317 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/impl/GreetingServiceImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common.impl;
import org.apache.dubbo.test.common.api.GreetingService;
/**
*
*/
public class GreetingServiceImpl implements GreetingService {
@Override
public String hello() {
return "Greetings!";
}
}
| 7,318 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/utils/TestSocketUtils.java
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common.utils;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.security.SecureRandom;
import javax.net.ServerSocketFactory;
import org.apache.dubbo.common.utils.Assert;
/**
* Simple utility for finding available TCP ports on {@code localhost} for use in
* integration testing scenarios.
*
* <p>{@code TestSocketUtils} can be used in integration tests which start an
* external server on an available random port. However, these utilities make no
* guarantee about the subsequent availability of a given port and are therefore
* unreliable. Instead of using {@code TestSocketUtils} to find an available local
* port for a server, it is recommended that you rely on a server's ability to
* start on a random <em>ephemeral</em> port that it selects or is assigned by the
* operating system. To interact with that server, you should query the server
* for the port it is currently using.
*
* @since 3.2
*/
public class TestSocketUtils {
/**
* The minimum value for port ranges used when finding an available TCP port.
*/
static final int PORT_RANGE_MIN = 1024;
/**
* The maximum value for port ranges used when finding an available TCP port.
*/
static final int PORT_RANGE_MAX = 65535;
private static final int PORT_RANGE_PLUS_ONE = PORT_RANGE_MAX - PORT_RANGE_MIN + 1;
private static final int MAX_ATTEMPTS = 1_000;
private static final SecureRandom random = new SecureRandom();
private static final TestSocketUtils INSTANCE = new TestSocketUtils();
private TestSocketUtils() {
}
/**
* Find an available TCP port randomly selected from the range [1024, 65535].
* @return an available TCP port number
* @throws IllegalStateException if no available port could be found
*/
public static int findAvailableTcpPort() {
return INSTANCE.findAvailableTcpPortInternal();
}
/**
* Internal implementation of {@link #findAvailableTcpPort()}.
* <p>Package-private solely for testing purposes.
*/
int findAvailableTcpPortInternal() {
int candidatePort;
int searchCounter = 0;
do {
Assert.assertTrue(++searchCounter <= MAX_ATTEMPTS, String.format(
"Could not find an available TCP port in the range [%d, %d] after %d attempts",
PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS));
candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE_PLUS_ONE);
}
while (!isPortAvailable(candidatePort));
return candidatePort;
}
/**
* Determine if the specified TCP port is currently available on {@code localhost}.
* <p>Package-private solely for testing purposes.
*/
boolean isPortAvailable(int port) {
try {
ServerSocket serverSocket = ServerSocketFactory.getDefault()
.createServerSocket(port, 1, InetAddress.getByName("localhost"));
serverSocket.close();
return true;
}
catch (Exception ex) {
return false;
}
}
}
| 7,319 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/GreetingService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common.api;
/**
*
*/
public interface GreetingService {
String hello();
}
| 7,320 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/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.test.common.api;
import java.util.concurrent.CompletableFuture;
public interface DemoService {
String sayHello(String name);
CompletableFuture<String> sayHelloAsync(String name);
}
| 7,321 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common
|
Create_ds/dubbo/dubbo-test/dubbo-test-common/src/main/java/org/apache/dubbo/test/common/api/RestDemoService.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.common.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/demoService")
public interface RestDemoService {
@GET
@Path("/hello")
Integer hello(@QueryParam("a") Integer a, @QueryParam("b") Integer b);
@GET
@Path("/error")
String error();
@POST
@Path("/say")
@Consumes({MediaType.TEXT_PLAIN})
String sayHello(String name);
@GET
@Path("/getRemoteApplicationName")
String getRemoteApplicationName();
}
| 7,322 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringAnnotationBeanTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.spring;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.test.common.api.DemoService;
import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
public class SpringAnnotationBeanTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(TestConfiguration.class);
TestService testService = applicationContext.getBean(TestService.class);
testService.test();
// check initialization customizer
MockSpringInitCustomizer.checkCustomizer(applicationContext);
}
@EnableDubbo(scanBasePackages = "org.apache.dubbo.test.common.impl")
@Configuration
@PropertySource("/demo-app.properties")
static class TestConfiguration {
@Bean
public TestService testService() {
return new TestService();
}
}
static class TestService {
@DubboReference
private DemoService demoService;
public void test() {
String result = demoService.sayHello("dubbo");
Assertions.assertEquals("Hello dubbo", result);
}
}
}
| 7,323 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringJavaConfigBeanTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.spring;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import org.apache.dubbo.test.common.SysProps;
import org.apache.dubbo.test.common.api.DemoService;
import org.apache.dubbo.test.common.impl.DemoServiceImpl;
import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer;
import java.util.Collection;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class SpringJavaConfigBeanTest {
private static final String MY_PROTOCOL_ID = "myProtocol";
private static final String MY_REGISTRY_ID = "my-registry";
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
}
@AfterEach
public void afterEach() {
SysProps.clear();
}
@Test
public void testBean() {
SysProps.setProperty("dubbo.application.owner", "Tom");
SysProps.setProperty("dubbo.application.qos-enable", "false");
SysProps.setProperty("dubbo.protocol.name", "dubbo");
SysProps.setProperty("dubbo.protocol.port", "2346");
String registryAddress = ZookeeperRegistryCenterConfig.getConnectionAddress();
SysProps.setProperty("dubbo.registry.address", registryAddress);
SysProps.setProperty("dubbo.provider.group", "test");
AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(
TestConfiguration.class, ConsumerConfiguration.class, ProviderConfiguration.class);
try {
consumerContext.start();
ApplicationModel applicationModel = consumerContext.getBean(ApplicationModel.class);
ConfigManager configManager = consumerContext.getBean(ConfigManager.class);
ApplicationConfig application = configManager.getApplication().get();
Assertions.assertEquals(false, application.getQosEnable());
Assertions.assertEquals("Tom", application.getOwner());
RegistryConfig registry = configManager.getRegistry(MY_REGISTRY_ID).get();
Assertions.assertEquals(registryAddress, registry.getAddress());
Collection<ProtocolConfig> protocols = configManager.getProtocols();
Assertions.assertEquals(1, protocols.size());
ProtocolConfig protocolConfig = protocols.iterator().next();
Assertions.assertEquals("dubbo", protocolConfig.getName());
Assertions.assertEquals(2346, protocolConfig.getPort());
Assertions.assertEquals(MY_PROTOCOL_ID, protocolConfig.getId());
ModuleConfigManager moduleConfigManager =
applicationModel.getDefaultModule().getConfigManager();
ConsumerConfig consumerConfig =
moduleConfigManager.getDefaultConsumer().get();
Assertions.assertEquals(1000, consumerConfig.getTimeout());
Assertions.assertEquals("demo", consumerConfig.getGroup());
Assertions.assertEquals(false, consumerConfig.isCheck());
Assertions.assertEquals(2, consumerConfig.getRetries());
Map<String, ReferenceBean> referenceBeanMap = consumerContext.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&demoService");
Assertions.assertNotNull(referenceBean);
ReferenceConfig referenceConfig = referenceBean.getReferenceConfig();
// use consumer's attributes as default value
Assertions.assertEquals(consumerConfig.getTimeout(), referenceConfig.getTimeout());
Assertions.assertEquals(consumerConfig.getGroup(), referenceConfig.getGroup());
// consumer cannot override reference's attribute
Assertions.assertEquals(5, referenceConfig.getRetries());
DemoService referProxy = (DemoService) referenceConfig.get();
Assertions.assertTrue(referProxy instanceof DemoService);
String result = referProxy.sayHello("dubbo");
Assertions.assertEquals("Hello dubbo", result);
// check initialization customizer
MockSpringInitCustomizer.checkCustomizer(consumerContext);
} finally {
consumerContext.close();
}
}
@EnableDubbo(scanBasePackages = "")
@Configuration
static class TestConfiguration {
@Bean(name = "dubbo-demo-application")
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo-demo-application");
return applicationConfig;
}
@Bean(name = MY_PROTOCOL_ID)
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("rest");
protocolConfig.setPort(1234);
return protocolConfig;
}
@Bean(name = MY_REGISTRY_ID)
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
return registryConfig;
}
@Bean
public ConsumerConfig consumerConfig() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setTimeout(1000);
consumer.setGroup("demo");
consumer.setCheck(false);
consumer.setRetries(2);
return consumer;
}
}
@Configuration
static class ConsumerConfiguration {
@Bean
@DubboReference(scope = Constants.SCOPE_LOCAL, retries = 5)
public ReferenceBean<DemoService> demoService() {
return new ReferenceBean<>();
}
}
@Configuration
static class ProviderConfiguration {
@Bean
@DubboService(group = "demo")
public DemoService demoServiceImpl() {
return new DemoServiceImpl();
}
}
}
| 7,324 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/SpringXmlConfigTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.spring;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.test.common.SysProps;
import org.apache.dubbo.test.common.api.DemoService;
import org.apache.dubbo.test.common.api.GreetingService;
import org.apache.dubbo.test.common.api.RestDemoService;
import org.apache.dubbo.test.spring.context.MockSpringInitCustomizer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
@DisabledForJreRange(min = JRE.JAVA_16)
public class SpringXmlConfigTest {
private static ClassPathXmlApplicationContext providerContext;
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
providerContext.close();
}
private void startProvider() {
providerContext = new ClassPathXmlApplicationContext("/spring/dubbo-demo-provider.xml");
}
@Test
public void test() {
SysProps.setProperty(SHUTDOWN_WAIT_KEY, "2000");
// start provider context
startProvider();
// start consumer context
ClassPathXmlApplicationContext applicationContext = null;
try {
applicationContext = new ClassPathXmlApplicationContext("/spring/dubbo-demo.xml");
GreetingService greetingService = applicationContext.getBean("greetingService", GreetingService.class);
String greeting = greetingService.hello();
Assertions.assertEquals(greeting, "Greetings!");
DemoService demoService = applicationContext.getBean("demoService", DemoService.class);
String sayHelloResult = demoService.sayHello("dubbo");
Assertions.assertTrue(sayHelloResult.startsWith("Hello dubbo"), sayHelloResult);
RestDemoService restDemoService = applicationContext.getBean("restDemoService", RestDemoService.class);
String resetHelloResult = restDemoService.sayHello("dubbo");
Assertions.assertEquals("Hello, dubbo", resetHelloResult);
// check initialization customizer
MockSpringInitCustomizer.checkCustomizer(applicationContext);
} finally {
SysProps.clear();
if (applicationContext != null) {
applicationContext.close();
}
}
}
}
| 7,325 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring
|
Create_ds/dubbo/dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.spring.context;
import org.apache.dubbo.config.spring.context.DubboSpringInitContext;
import org.apache.dubbo.config.spring.context.DubboSpringInitCustomizer;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.ConfigurableApplicationContext;
public class MockSpringInitCustomizer implements DubboSpringInitCustomizer {
private List<DubboSpringInitContext> contexts = new ArrayList<>();
@Override
public void customize(DubboSpringInitContext context) {
this.contexts.add(context);
// register post-processor bean, expecting the bean is loaded and invoked by spring container
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(
CustomBeanFactoryPostProcessor.class)
.getBeanDefinition();
context.getRegistry().registerBeanDefinition(CustomBeanFactoryPostProcessor.class.getName(), beanDefinition);
}
public List<DubboSpringInitContext> getContexts() {
return contexts;
}
private static class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
public static void checkCustomizer(ConfigurableApplicationContext applicationContext) {
Set<DubboSpringInitCustomizer> customizers = FrameworkModel.defaultModel()
.getExtensionLoader(DubboSpringInitCustomizer.class)
.getSupportedExtensionInstances();
MockSpringInitCustomizer mockCustomizer = null;
for (DubboSpringInitCustomizer customizer : customizers) {
if (customizer instanceof MockSpringInitCustomizer) {
mockCustomizer = (MockSpringInitCustomizer) customizer;
break;
}
}
Assertions.assertNotNull(mockCustomizer);
// check applicationContext
boolean foundInitContext = false;
List<DubboSpringInitContext> contexts = mockCustomizer.getContexts();
for (DubboSpringInitContext initializationContext : contexts) {
if (initializationContext.getRegistry() == applicationContext.getBeanFactory()) {
foundInitContext = true;
break;
}
}
Assertions.assertEquals(true, foundInitContext);
// expect CustomBeanFactoryPostProcessor is loaded and invoked
CustomBeanFactoryPostProcessor customBeanFactoryPostProcessor =
applicationContext.getBean(CustomBeanFactoryPostProcessor.class);
Assertions.assertEquals(applicationContext.getBeanFactory(), customBeanFactoryPostProcessor.beanFactory);
}
}
| 7,326 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/AbstractRegistryCenterTestExecutionListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check;
import java.util.HashSet;
import java.util.Set;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
/**
* The abstract implementation provides the basic methods. <p></p>
* {@link #needRegistryCenter(TestPlan)}: checks if current {@link TestPlan} need registry center.
*/
public abstract class AbstractRegistryCenterTestExecutionListener implements TestExecutionListener {
/**
* The JVM arguments to set if it can use embedded zookeeper, the default value is {@code true}.
*/
private static final String CONFIG_ENABLE_EMBEDDED_ZOOKEEPER = "enableEmbeddedZookeeper";
/**
* The registry center should start
* if we want to run the test cases in the given package.
*/
private static final Set<String> PACKAGE_NAME = new HashSet<>();
/**
* Use embedded zookeeper or not.
*/
private static boolean enableEmbeddedZookeeper;
static {
// dubbo-config module
PACKAGE_NAME.add("org.apache.dubbo.config");
// dubbo-test module
PACKAGE_NAME.add("org.apache.dubbo.test");
// dubbo-registry
PACKAGE_NAME.add("org.apache.dubbo.registry");
// dubbo-remoting-zookeeper
PACKAGE_NAME.add("org.apache.dubbo.remoting.zookeeper");
// dubbo-metadata-report-zookeeper
PACKAGE_NAME.add("org.apache.dubbo.metadata.store.zookeeper");
enableEmbeddedZookeeper = Boolean.valueOf(System.getProperty(CONFIG_ENABLE_EMBEDDED_ZOOKEEPER, "true"));
}
/**
* Checks if current {@link TestPlan} need registry center.
*/
public boolean needRegistryCenter(TestPlan testPlan) {
return testPlan.getRoots().stream()
.flatMap(testIdentifier -> testPlan.getChildren(testIdentifier).stream())
.filter(testIdentifier -> testIdentifier.getSource().isPresent())
.filter(testIdentifier -> supportEmbeddedZookeeper(testIdentifier))
.count()
> 0;
}
/**
* Checks if current {@link TestIdentifier} need registry center.
*/
public boolean needRegistryCenter(TestIdentifier testIdentifier) {
return supportEmbeddedZookeeper(testIdentifier);
}
/**
* Checks if the current {@link TestIdentifier} need embedded zookeeper.
*/
private boolean supportEmbeddedZookeeper(TestIdentifier testIdentifier) {
if (!enableEmbeddedZookeeper) {
return false;
}
TestSource testSource = testIdentifier.getSource().orElse(null);
if (testSource instanceof ClassSource) {
String packageName =
((ClassSource) testSource).getJavaClass().getPackage().getName();
for (String pkgName : PACKAGE_NAME) {
if (packageName.contains(pkgName)) {
return true;
}
}
}
return false;
}
}
| 7,327 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/DubboTestChecker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.TestSource;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.engine.support.descriptor.MethodSource;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
/**
* A test listener to check unclosed threads of test.
*
* <pre>
* Usages:
* # enable thread checking
* mvn test -DcheckThreads=true
*
* # change thread dump wait time (ms)
* mvn test -DcheckThreads=true -DthreadDumpWaitTime=5000
*
* # print test reports of all sub modules to single file
* mvn test -DcheckThreads=true -DthreadDumpWaitTime=5000 -DreportFile=/path/test-check-report.txt
* </pre>
*/
public class DubboTestChecker implements TestExecutionListener {
private static final String CONFIG_CHECK_MODE = "checkMode";
private static final String CONFIG_CHECK_THREADS = "checkThreads";
private static final String CONFIG_THREAD_DUMP_WAIT_TIME = "threadDumpWaitTime";
private static final String CONFIG_FORCE_DESTROY = "forceDestroy";
private static final String CONFIG_REPORT_FILE = "reportFile";
private static final String MODE_CLASS = "class";
private static final String MODE_METHOD = "method";
private static final Logger logger = LoggerFactory.getLogger(DubboTestChecker.class);
/**
* check mode:
* class - check after class execution finished
* method - check after method execution finished
*/
private String checkMode;
/**
* whether check unclosed threads
*/
private boolean checkThreads;
/**
* sleep time before dump threads
*/
private long threadDumpWaitTimeMs;
/**
* whether force destroy dubbo engine, default value is true.
*/
private boolean forceDestroyDubboAfterClass;
/**
* Check report file
*/
private File reportFile;
/**
* thread -> stacktrace
*/
private Map<Thread, StackTraceElement[]> unclosedThreadMap = new ConcurrentHashMap<>();
// test class name -> thread list
private Map<String, List<Thread>> unclosedThreadsOfTestMap = new ConcurrentHashMap<>();
private String identifier;
private PrintWriter reportWriter;
private String projectDir;
private FileOutputStream reportFileOut;
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
try {
init(System.getProperties());
} catch (IOException e) {
throw new IllegalStateException("Test checker init failed", e);
}
}
public void init(Properties properties) throws IOException {
if (properties == null) {
properties = new Properties();
}
// log prefix
identifier = "[" + this.getClass().getSimpleName() + "] ";
// checkMode: class/method
checkMode = StringUtils.lowerCase(properties.getProperty(CONFIG_CHECK_MODE, MODE_CLASS));
// checkThreads: true/false
checkThreads = Boolean.parseBoolean(properties.getProperty(CONFIG_CHECK_THREADS, "false"));
// threadDumpWaitTime
threadDumpWaitTimeMs = Long.parseLong(properties.getProperty(CONFIG_THREAD_DUMP_WAIT_TIME, "5000"));
// force destroy dubbo
forceDestroyDubboAfterClass = Boolean.parseBoolean(properties.getProperty(CONFIG_FORCE_DESTROY, "true"));
// project dir
projectDir = new File(".").getCanonicalPath();
// report file
String reportFileCanonicalPath = "";
String defaultReportDir = "target/";
String defaultReportFileName = "test-check-report.txt";
if (checkThreads) {
String reportFilePath =
properties.getProperty(CONFIG_REPORT_FILE, defaultReportDir + defaultReportFileName);
this.reportFile = new File(reportFilePath);
if (reportFile.isDirectory()) {
reportFile.mkdirs();
reportFile = new File(reportFile, defaultReportFileName);
}
reportFileOut = new FileOutputStream(this.reportFile);
reportWriter = new PrintWriter(reportFileOut);
reportFileCanonicalPath = reportFile.getCanonicalPath();
}
log("Project dir: " + projectDir);
log(String.format(
"Dubbo test checker configs: checkMode=%s, checkThreads=%s, threadDumpWaitTimeMs=%s, forceDestroy=%s, reportFile=%s",
checkMode, checkThreads, threadDumpWaitTimeMs, forceDestroyDubboAfterClass, reportFileCanonicalPath));
flushReportFile();
}
@Override
public void testPlanExecutionFinished(TestPlan testPlan) {
// print all unclosed threads
if (checkThreads) {
printThreadCheckingSummaryReport();
} else {
log("Thread checking is disabled, use -DcheckThreads=true to check unclosed threads.");
}
if (reportWriter != null) {
reportWriter.close();
}
}
private void printThreadCheckingSummaryReport() {
log("===== Thread Checking Summary Report ======");
log("Project dir: " + projectDir);
log("Total found " + unclosedThreadMap.size() + " unclosed threads in " + unclosedThreadsOfTestMap.size()
+ " tests.");
log("");
unclosedThreadsOfTestMap.forEach((testClassName, threads) -> {
printUnclosedThreads(threads, testClassName);
});
flushReportFile();
}
private void flushReportFile() {
try {
if (reportWriter != null) {
reportWriter.flush();
}
if (reportFileOut != null) {
reportFileOut.getFD().sync();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Map<Thread, StackTraceElement[]> getUnclosedThreadMap() {
return unclosedThreadMap;
}
@Override
public void executionStarted(TestIdentifier testIdentifier) {
TestSource testSource = testIdentifier.getSource().orElse(null);
if (testSource instanceof ClassSource) {
// ClassSource source = (ClassSource) testSource;
// log("Run test class: " + source.getClassName());
} else if (testSource instanceof MethodSource) {
MethodSource source = (MethodSource) testSource;
log("Run test method: " + source.getClassName() + "#" + source.getMethodName());
}
}
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
TestSource testSource = testIdentifier.getSource().orElse(null);
String testClassName;
if (testSource instanceof MethodSource) {
if (!StringUtils.contains(checkMode, MODE_METHOD)) {
return;
}
MethodSource methodSource = (MethodSource) testSource;
testClassName = methodSource.getClassName();
// log("Finish test method: " + methodSource.getClassName() + "#" + methodSource.getMethodName());
} else if (testSource instanceof ClassSource) {
if (forceDestroyDubboAfterClass) {
// make sure destroy dubbo engine
FrameworkModel.destroyAll();
}
if (!StringUtils.contains(checkMode, MODE_CLASS)) {
return;
}
ClassSource source = (ClassSource) testSource;
testClassName = source.getClassName();
// log("Finish test class: " + source.getClassName());
} else {
return;
}
if (checkThreads) {
checkUnclosedThreads(testClassName, threadDumpWaitTimeMs);
}
}
public Map<Thread, StackTraceElement[]> checkUnclosedThreads(String testClassName, long waitMs) {
// wait for shutdown
log("Wait " + waitMs + "ms to check threads of " + testClassName + " ...");
try {
Thread.sleep(waitMs);
} catch (InterruptedException e) {
}
Map<Thread, StackTraceElement[]> threadStacks = Thread.getAllStackTraces();
List<Thread> unclosedThreads = threadStacks.keySet().stream()
.filter(thread -> !StringUtils.startsWithAny(
thread.getName(),
"Reference Handler",
"Finalizer",
"Signal Dispatcher",
"Attach Listener",
"process reaper",
"main" // jvm
,
"surefire-forkedjvm-" // surefire plugin
))
.filter(thread -> !unclosedThreadMap.containsKey(thread))
.collect(Collectors.toList());
unclosedThreads.sort(Comparator.comparing(Thread::getName));
if (unclosedThreads.size() > 0) {
for (Thread thread : unclosedThreads) {
unclosedThreadMap.put(thread, threadStacks.get(thread));
}
unclosedThreadsOfTestMap.put(testClassName, unclosedThreads);
printUnclosedThreads(unclosedThreads, testClassName);
}
// return new unclosed thread map
Map<Thread, StackTraceElement[]> unclosedThreadMap = new LinkedHashMap<>();
for (Thread thread : unclosedThreads) {
unclosedThreadMap.put(thread, threadStacks.get(thread));
}
return unclosedThreadMap;
}
private void printUnclosedThreads(List<Thread> threads, String testClassName) {
if (threads.size() > 0) {
log("Found " + threads.size() + " unclosed threads in test: " + testClassName);
for (Thread thread : threads) {
StackTraceElement[] stackTrace = unclosedThreadMap.get(thread);
log(getFullStacktrace(thread, stackTrace));
}
flushReportFile();
}
}
private void log(String msg) {
// logger.info(identifier + msg);
String s = identifier + msg;
System.out.println(s);
if (reportWriter != null) {
reportWriter.println(s);
}
}
public static String getFullStacktrace(Thread thread, StackTraceElement[] stackTrace) {
StringBuilder sb = new StringBuilder("Thread: \"" + thread.getName() + "\"" + " Id=" + thread.getId());
sb.append(' ').append(thread.getState());
sb.append('\n');
if (stackTrace == null) {
stackTrace = thread.getStackTrace();
}
for (StackTraceElement ste : stackTrace) {
sb.append(" at ").append(ste.toString());
sb.append('\n');
}
return sb.toString();
}
}
| 7,328 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterFinished.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check;
import org.apache.dubbo.test.check.registrycenter.GlobalRegistryCenter;
import org.junit.platform.launcher.TestPlan;
/**
* The entrance to terminate the mocked registry center.
*/
public class RegistryCenterFinished extends AbstractRegistryCenterTestExecutionListener {
@Override
public void testPlanExecutionFinished(TestPlan testPlan) {
super.testPlanExecutionFinished(testPlan);
try {
if (needRegistryCenter(testPlan)) {
GlobalRegistryCenter.shutdown();
}
} catch (Throwable cause) {
throw new IllegalStateException("Failed to terminate zookeeper instance in unit test", cause);
}
}
}
| 7,329 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/RegistryCenterStarted.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check;
import org.apache.dubbo.test.check.registrycenter.GlobalRegistryCenter;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
/**
* The entrance to start the mocked registry center.
*/
public class RegistryCenterStarted extends AbstractRegistryCenterTestExecutionListener {
@Override
public void testPlanExecutionStarted(TestPlan testPlan) {
try {
if (needRegistryCenter(testPlan)) {
GlobalRegistryCenter.startup();
}
} catch (Throwable cause) {
throw new IllegalStateException("Failed to start zookeeper instance in unit test", cause);
}
}
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
try {
if (needRegistryCenter(testIdentifier)) {
GlobalRegistryCenter.reset();
}
} catch (Throwable cause) {
// ignore the exception
}
}
}
| 7,330 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext;
import org.apache.dubbo.test.check.registrycenter.initializer.ConfigZookeeperInitializer;
import org.apache.dubbo.test.check.registrycenter.initializer.DownloadZookeeperInitializer;
import org.apache.dubbo.test.check.registrycenter.initializer.UnpackZookeeperInitializer;
import org.apache.dubbo.test.check.registrycenter.initializer.ZookeeperInitializer;
import org.apache.dubbo.test.check.registrycenter.processor.ResetZookeeperProcessor;
import org.apache.dubbo.test.check.registrycenter.processor.StartZookeeperUnixProcessor;
import org.apache.dubbo.test.check.registrycenter.processor.StartZookeeperWindowsProcessor;
import org.apache.dubbo.test.check.registrycenter.processor.StopZookeeperUnixProcessor;
import org.apache.dubbo.test.check.registrycenter.processor.StopZookeeperWindowsProcessor;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Build the registry center with embedded zookeeper, which is run by a new process.
*/
class ZookeeperRegistryCenter implements RegistryCenter {
public ZookeeperRegistryCenter() {
this.initializers = new ArrayList<>();
this.initializers.add(new DownloadZookeeperInitializer());
this.initializers.add(new UnpackZookeeperInitializer());
this.initializers.add(new ConfigZookeeperInitializer());
// start processor
this.put(OS.Unix, Command.Start, new StartZookeeperUnixProcessor());
this.put(OS.Windows, Command.Start, new StartZookeeperWindowsProcessor());
// reset processor
Processor resetProcessor = new ResetZookeeperProcessor();
this.put(OS.Unix, Command.Reset, resetProcessor);
this.put(OS.Windows, Command.Reset, resetProcessor);
// stop processor
this.put(OS.Unix, Command.Stop, new StopZookeeperUnixProcessor());
this.put(OS.Windows, Command.Stop, new StopZookeeperWindowsProcessor());
// initialize the global context
if (OS.Unix.equals(os)) {
this.context = new ZookeeperContext();
} else {
this.context = new ZookeeperWindowsContext();
}
// initialize the context
this.context.setUnpackedDirectory(UNPACKED_DIRECTORY);
this.context.setSourceFile(TARGET_FILE_PATH);
}
private static final Logger logger = LoggerFactory.getLogger(ZookeeperRegistryCenter.class);
/**
* The JVM arguments to set the embedded zookeeper directory.
*/
private static final String CONFIG_EMBEDDED_ZOOKEEPER_DIRECTORY = "embeddedZookeeperPath";
/**
* The OS type.
*/
private static OS os = getOS();
/**
* All of {@link ZookeeperInitializer} instances.
*/
private List<Initializer> initializers;
/**
* The global context of zookeeper.
*/
private ZookeeperContext context;
/**
* To store all processor instances.
*/
private Map<OS, Map<Command, Processor>> processors = new HashMap<>();
/**
* The default unpacked directory.
*/
private static final String UNPACKED_DIRECTORY = "apache-zookeeper-bin";
/**
* The target name of zookeeper binary file.
*/
private static final String TARGET_ZOOKEEPER_FILE_NAME = UNPACKED_DIRECTORY + ".tar.gz";
/**
* The path of target zookeeper binary file.
*/
private static final Path TARGET_FILE_PATH = getTargetFilePath();
/**
* The {@link #INITIALIZED} for flagging the {@link #startup()} method is called or not.
*/
private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);
/**
* Returns the directory to store zookeeper binary archive.
* <p>The priorities to obtain the directory are as follows:</p>
* <p>1. Use System.getProperty({@link #CONFIG_EMBEDDED_ZOOKEEPER_DIRECTORY}) if not null or empty</p>
* <p>2. Use System.getProperty(user.home) if not null or empty</p>
* <p>3. Use System.getProperty(java.io.tmpdir)</p>
*/
private static String getEmbeddedZookeeperDirectory() {
String directory;
// Use System.getProperty({@link #CONFIG_EMBEDDED_ZOOKEEPER_DIRECTORY})
directory = System.getProperty(CONFIG_EMBEDDED_ZOOKEEPER_DIRECTORY);
logger.info(String.format("The customized directory is %s to store zookeeper binary archive.", directory));
if (StringUtils.isNotEmpty(directory)) {
return directory;
}
// Use System.getProperty(user.home)
logger.info(String.format("The user home is %s to store zookeeper binary archive.", directory));
directory = System.getProperty("user.home");
logger.info(String.format("user.home is %s", directory));
if (StringUtils.isEmpty(directory)) {
// Use default temporary directory
directory = System.getProperty("java.io.tmpdir");
logger.info(String.format("The temporary directory is %s to store zookeeper binary archive.", directory));
}
Assert.notEmptyString(directory, "The directory to store zookeeper binary archive cannot be null or empty.");
return directory + File.separator + ".tmp" + File.separator + "zookeeper";
}
/**
* Returns the target file path.
*/
private static Path getTargetFilePath() {
String zookeeperDirectory = getEmbeddedZookeeperDirectory();
Path targetFilePath = Paths.get(zookeeperDirectory, TARGET_ZOOKEEPER_FILE_NAME);
logger.info("Target file's absolute directory: " + targetFilePath);
return targetFilePath;
}
/**
* Returns the Operating System.
*/
private static OS getOS() {
String osName = System.getProperty("os.name").toLowerCase();
OS os = OS.Unix;
if (osName.contains("windows")) {
os = OS.Windows;
}
return os;
}
/**
* Store all initialized processor instances.
*
* @param os the {@link OS} type.
* @param command the {@link Command} to execute.
* @param processor the {@link Processor} to run.
*/
private void put(OS os, Command command, Processor processor) {
Map<Command, Processor> commandProcessorMap = this.processors.get(os);
if (commandProcessorMap == null) {
commandProcessorMap = new HashMap<>();
this.processors.put(os, commandProcessorMap);
}
commandProcessorMap.put(command, processor);
}
/**
* Gets the {@link Processor} with the given {@link OS} type and {@link Command}.
*
* @param os the {@link OS} type.
* @param command the {@link Command} to execute.
* @return the {@link Processor} to run.
*/
private Processor get(OS os, Command command) {
Map<Command, Processor> commandProcessorMap = this.processors.get(os);
Objects.requireNonNull(commandProcessorMap, "The command with the OS cannot be null");
Processor processor = commandProcessorMap.get(command);
Objects.requireNonNull(processor, "The processor cannot be null");
return processor;
}
/**
* {@inheritDoc}
*/
@Override
public void startup() throws DubboTestException {
if (!INITIALIZED.get()) {
// global look, make sure only one thread can initialize the zookeeper instances.
synchronized (ZookeeperRegistryCenter.class) {
if (!INITIALIZED.get()) {
for (Initializer initializer : this.initializers) {
initializer.initialize(this.context);
}
// add shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown()));
INITIALIZED.set(true);
}
}
}
this.get(os, Command.Start).process(this.context);
}
/**
* {@inheritDoc}
*/
@Override
public void reset() throws DubboTestException {
this.get(os, Command.Reset).process(this.context);
}
/**
* {@inheritDoc}
*/
@Override
public void shutdown() throws DubboTestException {
this.get(os, Command.Stop).process(this.context);
}
/**
* The type of OS.
*/
enum OS {
Windows,
Unix
}
/**
* The commands to support the zookeeper.
*/
enum Command {
Start,
Reset,
Stop
}
}
| 7,331 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/GlobalRegistryCenter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
/**
* The global registry center.
*/
public class GlobalRegistryCenter {
/**
* The default static registry center instance.
*/
private static final RegistryCenter INSTANCE = new ZookeeperRegistryCenter();
/**
* Start the registry center.
*
* @throws Exception when an exception occurred
*/
public static void startup() throws Exception {
INSTANCE.startup();
}
/**
* Reset the registry center.
*
* @throws Exception when an exception occurred
*/
public static void reset() throws Exception {
INSTANCE.reset();
}
/**
* Stop the registry center.
*
* @throws Exception when an exception occurred
*/
public static void shutdown() throws Exception {
INSTANCE.shutdown();
}
}
| 7,332 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Initializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
import org.apache.dubbo.test.check.exception.DubboTestException;
/**
* The purpose of this class is to do initialization when we build {@link RegistryCenter}.
*/
public interface Initializer {
/**
* Initialize the global context.
* @param context the global context to be initialized.
* @throws DubboTestException when any exception occurred.
*/
void initialize(Context context) throws DubboTestException;
}
| 7,333 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Context.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
/**
* The global context to store all initialized variables.
*/
public interface Context {}
| 7,334 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/RegistryCenter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
import org.apache.dubbo.test.check.exception.DubboTestException;
/**
* The registry center.
*/
public interface RegistryCenter {
/**
* Start the registry center.
*
* @throws DubboTestException when an exception occurred
*/
void startup() throws DubboTestException;
/**
* Reset the registry center after ut exited.
* @throws DubboTestException when an exception occurred
*/
void reset() throws DubboTestException;
/**
* Stop the registry center.
*
* @throws DubboTestException when an exception occurred
*/
void shutdown() throws DubboTestException;
}
| 7,335 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Processor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
import org.apache.dubbo.test.check.exception.DubboTestException;
/**
* Define the processor to execute {@link Process} with the {@link org.apache.dubbo.test.check.registrycenter.Initializer.Context}
*/
public interface Processor {
/**
* Process the command with the global context.
*
* @param context the global context.
* @throws DubboTestException when any exception occurred.
*/
void process(Context context) throws DubboTestException;
}
| 7,336 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/Config.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter;
/**
* Define the config to obtain the
*/
public interface Config {
/**
* Returns the default connection address in single registry center.
*/
default String getConnectionAddress() {
return getConnectionAddress1();
}
/**
* Returns the first connection address in multiple registry center.
*/
String getConnectionAddress1();
/**
* Returns the second connection address in multiple registry center.
*/
String getConnectionAddress2();
/**
* Returns the default connection address key in single registry center.
* <h3>How to use</h3>
* <pre>
* System.getProperty({@link #getConnectionAddressKey()})
* </pre>
*/
String getConnectionAddressKey();
/**
* Returns the first connection address key in multiple registry center.
* <h3>How to use</h3>
* <pre>
* System.getProperty({@link #getConnectionAddressKey1()})
* </pre>
*/
String getConnectionAddressKey1();
/**
* Returns the second connection address key in multiple registry center.
* <h3>How to use</h3>
* <pre>
* System.getProperty({@link #getConnectionAddressKey2()})
* </pre>
*/
String getConnectionAddressKey2();
}
| 7,337 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ZookeeperInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.initializer;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.Context;
import org.apache.dubbo.test.check.registrycenter.Initializer;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The implementation of {@link Initializer} to initialize zookeeper.
*/
public abstract class ZookeeperInitializer implements Initializer {
/**
* The {@link #INITIALIZED} for checking the {@link #initialize(Context)} method is called or not.
*/
private final AtomicBoolean INITIALIZED = new AtomicBoolean(false);
@Override
public void initialize(Context context) throws DubboTestException {
if (!this.INITIALIZED.compareAndSet(false, true)) {
return;
}
this.doInitialize((ZookeeperContext) context);
}
/**
* Initialize the global context for zookeeper.
*
* @param context the global context for zookeeper.
* @throws DubboTestException when any exception occurred.
*/
protected abstract void doInitialize(ZookeeperContext context) throws DubboTestException;
}
| 7,338 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.initializer;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.utils.IOUtils;
/**
* Unpack the downloaded zookeeper binary archive.
*/
public class UnpackZookeeperInitializer extends ZookeeperInitializer {
private static final Logger logger = LoggerFactory.getLogger(UnpackZookeeperInitializer.class);
/**
* Unpack the zookeeper binary file.
*
* @param context the global context of zookeeper.
* @param clientPort the client port
* @throws DubboTestException when an exception occurred
*/
private void unpack(ZookeeperContext context, int clientPort) throws DubboTestException {
File sourceFile = context.getSourceFile().toFile();
Path targetPath = Paths.get(context.getSourceFile().getParent().toString(), String.valueOf(clientPort));
// check if it's unpacked.
if (targetPath.toFile() != null && targetPath.toFile().isDirectory()) {
logger.info(String.format("The file has been unpacked, target path:%s", targetPath.toString()));
return;
}
try (FileInputStream fileInputStream = new FileInputStream(sourceFile);
GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream);
TarArchiveInputStream tarArchiveInputStream =
new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) {
File targetFile = targetPath.toFile();
TarArchiveEntry entry;
while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curFile = new File(targetFile, entry.getName());
File parent = curFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try (FileOutputStream outputStream = new FileOutputStream(curFile)) {
IOUtils.copy(tarArchiveInputStream, outputStream);
}
}
} catch (IOException e) {
throw new DubboTestException(String.format("Failed to unpack the zookeeper binary file"), e);
}
}
@Override
protected void doInitialize(ZookeeperContext context) throws DubboTestException {
for (int clientPort : context.getClientPorts()) {
this.unpack(context, clientPort);
// get the file name, just like apache-zookeeper-{version}-bin
// the version we maybe unknown if the zookeeper archive binary file is copied by user self.
Path parentPath = Paths.get(context.getSourceFile().getParent().toString(), String.valueOf(clientPort));
if (!Files.exists(parentPath)
|| !parentPath.toFile().isDirectory()
|| parentPath.toFile().listFiles().length != 1) {
throw new IllegalStateException("There is something wrong in unpacked file!");
}
// rename directory
File sourceFile = parentPath.toFile().listFiles()[0];
File targetFile = Paths.get(parentPath.toString(), context.getUnpackedDirectory())
.toFile();
sourceFile.renameTo(targetFile);
if (!Files.exists(targetFile.toPath()) || !targetFile.isDirectory()) {
throw new IllegalStateException(String.format(
"Failed to rename the directory. source directory: %s, target directory: %s",
sourceFile.toPath().toString(), targetFile.toPath().toString()));
}
// get the bin path
Path zookeeperBin = Paths.get(targetFile.toString(), "bin");
// update file permission
for (File file : zookeeperBin.toFile().listFiles()) {
file.setExecutable(true, false);
file.setReadable(true, false);
file.setWritable(false, false);
}
}
}
}
| 7,339 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/ConfigZookeeperInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.initializer;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
/**
* Update the config file of zookeeper.
*/
public class ConfigZookeeperInitializer extends ZookeeperInitializer {
private static final Logger logger = LoggerFactory.getLogger(ConfigZookeeperInitializer.class);
/**
* Update the config file with the given client port and admin server port.
*
* @param clientPort the client port
* @param adminServerPort the admin server port
* @throws DubboTestException when an exception occurred
*/
private void updateConfig(ZookeeperContext context, int clientPort, int adminServerPort) throws DubboTestException {
Path zookeeperConf = Paths.get(
context.getSourceFile().getParent().toString(),
String.valueOf(clientPort),
context.getUnpackedDirectory(),
"conf");
File zooSample = Paths.get(zookeeperConf.toString(), "zoo_sample.cfg").toFile();
int availableAdminServerPort = NetUtils.getAvailablePort(adminServerPort);
Properties properties = new Properties();
try {
// use Files.newInputStream instead of new FileInputStream
properties.load(Files.newInputStream(zooSample.toPath()));
properties.setProperty("clientPort", String.valueOf(clientPort));
properties.setProperty("admin.serverPort", String.valueOf(availableAdminServerPort));
Path dataDir = Paths.get(zookeeperConf.getParent().toString(), "data");
if (!Files.exists(dataDir)) {
try {
logger.info("It is creating the data directory...");
Files.createDirectories(dataDir);
} catch (IOException e) {
throw new RuntimeException(
String.format(
"Failed to create the data directory to save zookeeper binary file, file path:%s",
context.getSourceFile()),
e);
}
}
properties.setProperty("dataDir", dataDir.toString());
FileOutputStream oFile = null;
try {
oFile = new FileOutputStream(
Paths.get(zookeeperConf.toString(), "zoo.cfg").toFile());
properties.store(oFile, "");
} finally {
try {
oFile.close();
} catch (IOException e) {
throw new DubboTestException("Failed to close file", e);
}
}
logger.info("The configuration information of zoo.cfg are as below,\n" + "which located in "
+ zooSample.getAbsolutePath() + "\n" + propertiesToString(properties));
} catch (IOException e) {
throw new DubboTestException(String.format("Failed to update %s file", zooSample), e);
}
File log4j = Paths.get(zookeeperConf.toString(), "log4j.properties").toFile();
try {
// use Files.newInputStream instead of new FileInputStream
properties.load(Files.newInputStream(log4j.toPath()));
Path logDir = Paths.get(zookeeperConf.getParent().toString(), "logs");
if (!Files.exists(logDir)) {
try {
logger.info("It is creating the log directory...");
Files.createDirectories(logDir);
} catch (IOException e) {
throw new RuntimeException(
String.format(
"Failed to create the log directory to save zookeeper binary file, file path:%s",
context.getSourceFile()),
e);
}
}
properties.setProperty("zookeeper.log.dir", logDir.toString());
FileOutputStream oFile = null;
try {
oFile = new FileOutputStream(
Paths.get(zookeeperConf.toString(), "log4j.properties").toFile());
properties.store(oFile, "");
} finally {
try {
oFile.close();
} catch (IOException e) {
throw new DubboTestException("Failed to close file", e);
}
}
logger.info("The configuration information of log4j.properties are as below,\n" + "which located in "
+ log4j.getAbsolutePath() + "\n" + propertiesToString(properties));
} catch (IOException e) {
throw new DubboTestException(String.format("Failed to update %s file", zooSample), e);
}
}
/**
* Convert the {@link Properties} instance to {@link String}.
*
* @param properties the properties to convert.
* @return the string converted from {@link Properties} instance.
*/
private String propertiesToString(Properties properties) {
StringBuilder builder = new StringBuilder();
for (Object key : properties.keySet()) {
builder.append(key);
builder.append(": ");
builder.append(properties.get(key));
builder.append("\n");
}
return builder.toString();
}
@Override
protected void doInitialize(ZookeeperContext context) throws DubboTestException {
for (int i = 0; i < context.getClientPorts().length; i++) {
this.updateConfig(context, context.getClientPorts()[i], context.getAdminServerPorts()[i]);
}
}
}
| 7,340 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/DownloadZookeeperInitializer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.initializer;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
import org.asynchttpclient.Response;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE;
/**
* Download zookeeper binary archive.
*/
public class DownloadZookeeperInitializer extends ZookeeperInitializer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DownloadZookeeperInitializer.class);
/**
* The zookeeper binary file name format.
*/
private static final String ZOOKEEPER_FILE_NAME_FORMAT = "apache-zookeeper-%s-bin.tar.gz";
/**
* The url format for zookeeper binary file.
*/
private static final String ZOOKEEPER_BINARY_URL_FORMAT =
"https://archive.apache.org/dist/zookeeper/zookeeper-%s/" + ZOOKEEPER_FILE_NAME_FORMAT;
/**
* The temporary directory.
*/
private static final String TEMPORARY_DIRECTORY = "zookeeper";
/**
* The timeout when download zookeeper binary archive file.
*/
private static final int REQUEST_TIMEOUT = 30 * 1000;
/**
* The timeout when connect the download url.
*/
private static final int CONNECT_TIMEOUT = 10 * 1000;
/**
* Returns {@code true} if the file exists with the given file path, otherwise {@code false}.
*
* @param filePath the file path to check.
*/
private boolean checkFile(Path filePath) {
return Files.exists(filePath) && filePath.toFile().isFile();
}
@Override
protected void doInitialize(ZookeeperContext context) throws DubboTestException {
// checks the zookeeper binary file exists or not
if (checkFile(context.getSourceFile())) {
return;
}
String zookeeperFileName = String.format(ZOOKEEPER_FILE_NAME_FORMAT, context.getVersion());
Path temporaryFilePath;
try {
temporaryFilePath = Paths.get(
Files.createTempDirectory("").getParent().toString(), TEMPORARY_DIRECTORY, zookeeperFileName);
} catch (IOException e) {
throw new RuntimeException(
String.format("Cannot create the temporary directory, file path: %s", TEMPORARY_DIRECTORY), e);
}
// create the temporary directory path.
try {
Files.createDirectories(temporaryFilePath.getParent());
} catch (IOException e) {
throw new RuntimeException(
String.format(
"Failed to create the temporary directory to save zookeeper binary file, file path:%s",
temporaryFilePath.getParent()),
e);
}
// download zookeeper binary file in temporary directory.
String zookeeperBinaryUrl =
String.format(ZOOKEEPER_BINARY_URL_FORMAT, context.getVersion(), context.getVersion());
try {
logger.info("It is beginning to download the zookeeper binary archive, it will take several minutes..."
+ "\nThe zookeeper binary archive file will be download from "
+ zookeeperBinaryUrl + "," + "\nwhich will be saved in "
+ temporaryFilePath.toString() + ","
+ "\nalso it will be renamed to 'apache-zookeeper-bin.tar.gz' and moved into "
+ context.getSourceFile() + ".\n");
this.download(zookeeperBinaryUrl, temporaryFilePath);
} catch (Exception e) {
throw new RuntimeException(
String.format(
"Download zookeeper binary archive failed, download url:%s, file path:%s."
+ "\nOr you can do something to avoid this problem as below:"
+ "\n1. Download zookeeper binary archive manually regardless of the version"
+ "\n2. Rename the downloaded file named 'apache-zookeeper-{version}-bin.tar.gz' to 'apache-zookeeper-bin.tar.gz'"
+ "\n3. Put the renamed file in %s, you maybe need to create the directory if necessary.\n",
zookeeperBinaryUrl, temporaryFilePath, context.getSourceFile()),
e);
}
// check downloaded zookeeper binary file in temporary directory.
if (!checkFile(temporaryFilePath)) {
throw new IllegalArgumentException(String.format(
"There are some unknown problem occurred when downloaded the zookeeper binary archive file, file path:%s",
temporaryFilePath));
}
// create target directory if necessary
if (!Files.exists(context.getSourceFile())) {
try {
Files.createDirectories(context.getSourceFile().getParent());
} catch (IOException e) {
throw new IllegalArgumentException(
String.format(
"Failed to create target directory, the directory path: %s",
context.getSourceFile().getParent()),
e);
}
}
// copy the downloaded zookeeper binary file into the target file path
try {
Files.copy(temporaryFilePath, context.getSourceFile(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalArgumentException(
String.format(
"Failed to copy file, the source file path: %s, the target file path: %s",
temporaryFilePath, context.getSourceFile()),
e);
}
// checks the zookeeper binary file exists or not again
if (!checkFile(context.getSourceFile())) {
throw new IllegalArgumentException(String.format(
"The zookeeper binary archive file doesn't exist, file path:%s", context.getSourceFile()));
}
}
/**
* Download the file with the given url.
*
* @param url the url to download.
* @param targetPath the target path to save the downloaded file.
*/
private void download(String url, Path targetPath)
throws ExecutionException, InterruptedException, IOException, TimeoutException {
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(new DefaultAsyncHttpClientConfig.Builder()
.setConnectTimeout(CONNECT_TIMEOUT)
.setRequestTimeout(REQUEST_TIMEOUT)
.setMaxRequestRetry(1)
.build());
Future<Response> responseFuture = asyncHttpClient
.prepareGet(url)
.execute(new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response response) {
logger.info("Download zookeeper binary archive file successfully! download url: " + url);
return response;
}
@Override
public void onThrowable(Throwable t) {
logger.warn(
TESTING_REGISTRY_FAILED_TO_DOWNLOAD_ZK_FILE,
"",
"",
"Failed to download the file, download url: " + url);
super.onThrowable(t);
}
});
// Future timeout should 2 times as equal as REQUEST_TIMEOUT, because it will retry 1 time.
Response response = responseFuture.get(REQUEST_TIMEOUT * 2, TimeUnit.MILLISECONDS);
Files.copy(response.getResponseBodyAsStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
| 7,341 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperWindowsContext.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.context;
import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.exec.ExecuteWatchdog;
/**
* The global context for zookeeper on Windows OS.
*/
public class ZookeeperWindowsContext extends ZookeeperContext {
/**
* The default executor service to manage the lifecycle of zookeeper.
*/
private final ExecutorService DEFAULT_EXECUTOR_SERVICE = new ThreadPoolExecutor(
2,
2,
0,
TimeUnit.MILLISECONDS,
new SynchronousQueue<>(),
new NamedInternalThreadFactory("mocked-zookeeper", true),
new ThreadPoolExecutor.AbortPolicy());
/**
* Define the default {@link ExecuteWatchdog} for terminating all registered zookeeper processes.
*/
private final ExecuteWatchdog WATCHDOG = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
/**
* The map to store the pair of clientPort and PID.
*/
private Map<Integer, Integer> processIds = new HashMap<>();
/**
* Register the process id of zookeeper.
*
* @param clientPort the client port of zookeeper.
* @param pid the process id of zookeeper instance.
*/
public void register(int clientPort, int pid) {
this.processIds.put(clientPort, pid);
}
/**
* Returns the pid of zookeeper instance with the given client port.
*
* @param clientPort the client port of zookeeper instance.
* @return the pid of zookeeper instance.
*/
public Integer getPid(int clientPort) {
return this.processIds.get(clientPort);
}
/**
* Remove the registered pid with the given client port.
* @param clientPort the client port of zookeeper instance.
*/
public void removePid(int clientPort) {
this.processIds.remove(clientPort);
}
/**
* Returns the default executor service to manage the lifecycle of zookeeper.
*/
public ExecutorService getExecutorService() {
return DEFAULT_EXECUTOR_SERVICE;
}
/**
* Returns the {@link ExecuteWatchdog}.
*/
public ExecuteWatchdog getWatchdog() {
return WATCHDOG;
}
/**
* Destroy all registered resources.
*/
public void destroy() {
this.processIds.clear();
this.WATCHDOG.destroyProcess();
try {
DEFAULT_EXECUTOR_SERVICE.shutdownNow();
} catch (SecurityException | NullPointerException ex) {
return;
}
try {
DEFAULT_EXECUTOR_SERVICE.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
| 7,342 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/context/ZookeeperContext.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.context;
import org.apache.dubbo.test.check.registrycenter.Context;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperConfig;
import java.nio.file.Path;
/**
* The global context for zookeeper.
*/
public class ZookeeperContext implements Context {
/**
* The config of zookeeper.
*/
private ZookeeperConfig config = new ZookeeperConfig();
/**
* The the source file path of downloaded zookeeper binary archive.
*/
private Path sourceFile;
/**
* The directory after unpacked zookeeper archive binary file.
*/
private String unpackedDirectory;
/**
* Sets the source file path of downloaded zookeeper binary archive.
*/
public void setSourceFile(Path sourceFile) {
this.sourceFile = sourceFile;
}
/**
* Returns the source file path of downloaded zookeeper binary archive.
*/
public Path getSourceFile() {
return this.sourceFile;
}
/**
* Returns the directory after unpacked zookeeper archive binary file.
*/
public String getUnpackedDirectory() {
return unpackedDirectory;
}
/**
* Sets the directory after unpacked zookeeper archive binary file.
*/
public void setUnpackedDirectory(String unpackedDirectory) {
this.unpackedDirectory = unpackedDirectory;
}
/**
* Returns the zookeeper's version.
*/
public String getVersion() {
return config.getVersion();
}
/**
* Returns the client ports of zookeeper.
*/
public int[] getClientPorts() {
return config.getClientPorts();
}
/**
* Returns the admin server ports of zookeeper.
*/
public int[] getAdminServerPorts() {
return config.getAdminServerPorts();
}
}
| 7,343 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/config/ZookeeperRegistryCenterConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.config;
import org.apache.dubbo.test.check.registrycenter.Config;
/**
* Define the zookeeper global config for registry center.
*/
public class ZookeeperRegistryCenterConfig {
/**
* Define the {@link Config} instance.
*/
private static final Config CONFIG = new ZookeeperConfig();
/**
* Returns the connection address in single registry center.
*/
public static String getConnectionAddress() {
return CONFIG.getConnectionAddress();
}
/**
* Returns the first connection address in multiple registry centers.
*/
public static String getConnectionAddress1() {
return CONFIG.getConnectionAddress1();
}
/**
* Returns the second connection address in multiple registry centers.
*/
public static String getConnectionAddress2() {
return CONFIG.getConnectionAddress2();
}
/**
* Returns the default connection address key in single registry center.
* <h3>How to use</h3>
* <pre>
* System.getProperty({@link ZookeeperRegistryCenterConfig#getConnectionAddressKey()})
* </pre>
*/
public static String getConnectionAddressKey() {
return CONFIG.getConnectionAddressKey();
}
/**
* Returns the first connection address key in multiple registry center.
* <h3>How to use</h3>
* <pre>
* System.getProperty({@link ZookeeperRegistryCenterConfig#getConnectionAddressKey1()})
* </pre>
*/
public static String getConnectionAddressKey1() {
return CONFIG.getConnectionAddressKey1();
}
/**
* Returns the second connection address key in multiple registry center.
* <h3>How to use</h3>
* <pre>
* System.getProperty({@link ZookeeperRegistryCenterConfig#getConnectionAddressKey2()})
* </pre>
*/
public static String getConnectionAddressKey2() {
return CONFIG.getConnectionAddressKey2();
}
}
| 7,344 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/config/ZookeeperConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.config;
import org.apache.dubbo.test.check.registrycenter.Config;
/**
* The zookeeper config in registry center.
*/
public class ZookeeperConfig implements Config {
/**
* The system properties config key with zookeeper port.
*/
private static final String ZOOKEEPER_PORT_KEY = "zookeeper.port";
/**
* The system properties config key with first zookeeper port.
*/
private static final String ZOOKEEPER_PORT_1_KEY = "zookeeper.port.1";
/**
* The system properties config key with second zookeeper port.
*/
private static final String ZOOKEEPER_PORT_2_KEY = "zookeeper.port.2";
/**
* The system properties config key with zookeeper connection address.
*/
private static final String ZOOKEEPER_CONNECTION_ADDRESS_KEY = "zookeeper.connection.address";
/**
* The system properties config key with first zookeeper connection address.
*/
private static final String ZOOKEEPER_CONNECTION_ADDRESS_1_KEY = "zookeeper.connection.address.1";
/**
* The system properties config key with second zookeeper connection address.
*/
private static final String ZOOKEEPER_CONNECTION_ADDRESS_2_KEY = "zookeeper.connection.address.2";
/**
* The default first client port of zookeeper.
*/
public static final int DEFAULT_CLIENT_PORT_1 = 2181;
/**
* The default second client port of zookeeper.
*/
public static final int DEFAULT_CLIENT_PORT_2 = 2182;
/**
* The default client ports of zookeeper.
*/
private static final int[] CLIENT_PORTS = new int[2];
/**
* The default admin server ports of zookeeper.
*/
private static final int[] DEFAULT_ADMIN_SERVER_PORTS = new int[] {18081, 18082};
/**
* The default version of zookeeper.
*/
private static final String DEFAULT_ZOOKEEPER_VERSION = "3.6.0";
/**
* The format for zookeeper connection address.
*/
private static final String CONNECTION_ADDRESS_FORMAT = "zookeeper://127.0.0.1:%d";
// initialize the client ports of zookeeper.
static {
// There are two client ports
// The priority of the one is that get it from system properties config
// with the key of {@link #ZOOKEEPER_PORT_1_KEY} first, and then {@link #ZOOKEEPER_PORT_KEY},
// finally use {@link #DEFAULT_CLIENT_PORT_1} as default port
// The priority of the other is that get it from system properties config with the key of {@link
// #ZOOKEEPER_PORT_2_KEY} first,
// and then use {@link #DEFAULT_CLIENT_PORT_2} as default port
int port1 = DEFAULT_CLIENT_PORT_1;
int port2 = DEFAULT_CLIENT_PORT_2;
String portConfig1 = System.getProperty(ZOOKEEPER_PORT_1_KEY, System.getProperty(ZOOKEEPER_PORT_KEY));
if (portConfig1 != null) {
try {
port1 = Integer.parseInt(portConfig1);
} catch (NumberFormatException e) {
port1 = DEFAULT_CLIENT_PORT_1;
}
}
String portConfig2 = System.getProperty(ZOOKEEPER_PORT_2_KEY);
if (portConfig2 != null) {
try {
port2 = Integer.parseInt(portConfig2);
} catch (NumberFormatException e) {
port2 = DEFAULT_CLIENT_PORT_2;
}
}
if (port1 == port2) {
throw new IllegalArgumentException(
String.format("The client ports %d and %d of zookeeper cannot be same!", port1, port2));
}
CLIENT_PORTS[0] = port1;
CLIENT_PORTS[1] = port2;
// set system properties config
System.setProperty(ZOOKEEPER_CONNECTION_ADDRESS_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[0]));
System.setProperty(
ZOOKEEPER_CONNECTION_ADDRESS_1_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[0]));
System.setProperty(
ZOOKEEPER_CONNECTION_ADDRESS_2_KEY, String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[1]));
}
@Override
public String getConnectionAddress1() {
return String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[0]);
}
@Override
public String getConnectionAddress2() {
return String.format(CONNECTION_ADDRESS_FORMAT, CLIENT_PORTS[1]);
}
@Override
public String getConnectionAddressKey() {
return ZOOKEEPER_CONNECTION_ADDRESS_KEY;
}
@Override
public String getConnectionAddressKey1() {
return ZOOKEEPER_CONNECTION_ADDRESS_1_KEY;
}
@Override
public String getConnectionAddressKey2() {
return ZOOKEEPER_CONNECTION_ADDRESS_2_KEY;
}
/**
* Returns the zookeeper's version.
*/
public String getVersion() {
return DEFAULT_ZOOKEEPER_VERSION;
}
/**
* Returns the client ports of zookeeper.
*/
public int[] getClientPorts() {
return CLIENT_PORTS;
}
/**
* Returns the admin server ports of zookeeper.
*/
public int[] getAdminServerPorts() {
return DEFAULT_ADMIN_SERVER_PORTS;
}
}
| 7,345 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/KillProcessWindowsProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
/**
* Create a {@link org.apache.dubbo.test.check.registrycenter.Processor} to kill pid on Windows OS.
*/
public class KillProcessWindowsProcessor extends ZookeeperWindowsProcessor {
private static final Logger logger = LoggerFactory.getLogger(KillProcessWindowsProcessor.class);
@Override
protected void doProcess(ZookeeperWindowsContext context) throws DubboTestException {
for (int clientPort : context.getClientPorts()) {
Integer pid = context.getPid(clientPort);
if (pid == null) {
logger.info("There is no PID of zookeeper instance with the port " + clientPort);
continue;
}
logger.info(String.format("Kill the pid %d of the zookeeper with port %d", pid, clientPort));
Executor executor = new DefaultExecutor();
executor.setExitValues(null);
executor.setStreamHandler(new PumpStreamHandler(null, null, null));
CommandLine cmdLine = new CommandLine("cmd.exe");
cmdLine.addArgument("/c");
cmdLine.addArgument("taskkill /PID " + pid + " -t -f");
try {
executor.execute(cmdLine);
// clear pid
context.removePid(clientPort);
} catch (IOException e) {
throw new DubboTestException(
String.format("Failed to kill the pid %d of zookeeper with port %d", pid, clientPort), e);
}
}
}
}
| 7,346 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperUnixProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Create {@link Process} to start zookeeper on Unix OS.
*/
public class StartZookeeperUnixProcessor extends ZookeeperUnixProcessor {
private static final Logger logger = LoggerFactory.getLogger(StartZookeeperUnixProcessor.class);
/**
* The pattern for checking if zookeeper instances started.
*/
private static final Pattern PATTERN_STARTED = Pattern.compile(".*STARTED.*");
@Override
protected Process doProcess(ZookeeperContext context, int clientPort) throws DubboTestException {
logger.info(String.format("The zookeeper-%d is starting...", clientPort));
List<String> commands = new ArrayList<>();
Path zookeeperBin = Paths.get(
context.getSourceFile().getParent().toString(),
String.valueOf(clientPort),
context.getUnpackedDirectory(),
"bin");
commands.add(Paths.get(zookeeperBin.toString(), "zkServer.sh")
.toAbsolutePath()
.toString());
commands.add("start");
commands.add(Paths.get(zookeeperBin.getParent().toString(), "conf", "zoo.cfg")
.toAbsolutePath()
.toString());
try {
return new ProcessBuilder()
.directory(zookeeperBin.getParent().toFile())
.command(commands)
.inheritIO()
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.start();
} catch (IOException e) {
throw new DubboTestException(String.format("Failed to start zookeeper-%d", clientPort), e);
}
}
@Override
protected Pattern getPattern() {
return PATTERN_STARTED;
}
}
| 7,347 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperUnixProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.Context;
import org.apache.dubbo.test.check.registrycenter.Processor;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGISTRY_FAILED_TO_START_ZOOKEEPER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER;
/**
* The abstract implementation of {@link Processor} is to provide some common methods on Unix OS.
*/
public abstract class ZookeeperUnixProcessor implements Processor {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ZookeeperUnixProcessor.class);
@Override
public void process(Context context) throws DubboTestException {
ZookeeperContext zookeeperContext = (ZookeeperContext) context;
for (int clientPort : zookeeperContext.getClientPorts()) {
Process process = this.doProcess(zookeeperContext, clientPort);
this.logErrorStream(process.getErrorStream());
this.awaitProcessReady(process.getInputStream());
// kill the process
try {
process.destroy();
} catch (Throwable cause) {
logger.warn(
TESTING_REGISTRY_FAILED_TO_STOP_ZOOKEEPER,
"",
"",
String.format("Failed to kill the process, with client port %s !", clientPort),
cause);
}
}
}
/**
* Prints the error log after run {@link Process}.
*
* @param errorStream the error stream.
*/
private void logErrorStream(final InputStream errorStream) {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) {
String line;
while ((line = reader.readLine()) != null) {
logger.error(TESTING_REGISTRY_FAILED_TO_START_ZOOKEEPER, "", "", line);
}
} catch (IOException e) {
/* eat quietly */
}
}
/**
* Wait until the server is started successfully.
*
* @param inputStream the log after run {@link Process}.
* @throws DubboTestException if cannot match the given pattern.
*/
private void awaitProcessReady(final InputStream inputStream) throws DubboTestException {
final StringBuilder log = new StringBuilder();
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
if (this.getPattern().matcher(line).matches()) {
return;
}
log.append('\n').append(line);
}
} catch (IOException e) {
throw new DubboTestException("Failed to read the log after executed process.", e);
}
throw new DubboTestException("Ready pattern not found in log, log: " + log);
}
/**
* Use {@link Process} to handle the command.
*
* @param context the global zookeeper context.
* @param clientPort the client port of zookeeper.
* @return the instance of {@link Process}.
* @throws DubboTestException when any exception occurred.
*/
protected abstract Process doProcess(ZookeeperContext context, int clientPort) throws DubboTestException;
/**
* Gets the pattern to check the server is ready or not.
*
* @return the pattern for checking.
*/
protected abstract Pattern getPattern();
}
| 7,348 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StartZookeeperWindowsProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.Processor;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
/**
* Create {@link Process} to start zookeeper on Windows OS.
*/
public class StartZookeeperWindowsProcessor extends ZookeeperWindowsProcessor {
private static final Logger logger = LoggerFactory.getLogger(StartZookeeperWindowsProcessor.class);
/**
* The {@link Processor} to find the pid of zookeeper instance.
*/
private final Processor findPidProcessor = new FindPidWindowsProcessor();
/**
* The {@link Processor} to kill the pid of zookeeper instance.
*/
private final Processor killPidProcessor = new KillProcessWindowsProcessor();
@Override
protected void doProcess(ZookeeperWindowsContext context) throws DubboTestException {
// find pid and save into global context.
this.findPidProcessor.process(context);
// kill pid of zookeeper instance if exists
this.killPidProcessor.process(context);
for (int clientPort : context.getClientPorts()) {
logger.info(String.format("The zookeeper-%d is starting...", clientPort));
Path zookeeperBin = Paths.get(
context.getSourceFile().getParent().toString(),
String.valueOf(clientPort),
context.getUnpackedDirectory(),
"bin");
Executor executor = new DefaultExecutor();
executor.setExitValues(null);
executor.setWatchdog(context.getWatchdog());
CommandLine cmdLine = new CommandLine("cmd.exe");
cmdLine.addArgument("/c");
cmdLine.addArgument(Paths.get(zookeeperBin.toString(), "zkServer.cmd")
.toAbsolutePath()
.toString());
context.getExecutorService().submit(() -> executor.execute(cmdLine));
}
try {
// TODO: Help me to optimize the ugly sleep.
// sleep to wait all of zookeeper instances are started successfully.
// The best way is to check the output log with the specified keywords,
// however, there maybe keep waiting for check when any exception occurred,
// because the output stream will be blocked to wait for continuous data without any break
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// ignored
}
}
}
| 7,349 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ResetZookeeperProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.Context;
import org.apache.dubbo.test.check.registrycenter.Processor;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
/**
* Create {@link Process} to reset zookeeper.
*/
public class ResetZookeeperProcessor implements Processor {
@Override
public void process(Context context) throws DubboTestException {
ZookeeperContext zookeeperContext = (ZookeeperContext) context;
for (int clientPort : zookeeperContext.getClientPorts()) {
CuratorFramework client;
try {
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString("127.0.0.1:" + clientPort)
.retryPolicy(new RetryNTimes(1, 1000));
client = builder.build();
client.start();
boolean connected = client.blockUntilConnected(1000, TimeUnit.MILLISECONDS);
if (!connected) {
throw new IllegalStateException("zookeeper not connected");
}
client.delete().deletingChildrenIfNeeded().forPath("/dubbo");
} catch (Exception e) {
throw new DubboTestException(e.getMessage(), e);
}
}
}
}
| 7,350 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/FindPidWindowsProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
/**
* Create a {@link org.apache.dubbo.test.check.registrycenter.Processor} to find pid on Windows OS.
*/
public class FindPidWindowsProcessor extends ZookeeperWindowsProcessor {
private static final Logger logger = LoggerFactory.getLogger(FindPidWindowsProcessor.class);
@Override
protected void doProcess(ZookeeperWindowsContext context) throws DubboTestException {
for (int clientPort : context.getClientPorts()) {
this.findPid(context, clientPort);
}
}
/**
* Find the pid of zookeeper instance.
*
* @param context the global context.
* @param clientPort the client port of zookeeper instance.
*/
private void findPid(ZookeeperWindowsContext context, int clientPort) {
logger.info(String.format("Find the pid of the zookeeper with port %d", clientPort));
Executor executor = new DefaultExecutor();
executor.setExitValues(null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream ins = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(ins.toByteArray());
executor.setStreamHandler(new PumpStreamHandler(out, null, in));
CommandLine cmdLine = new CommandLine("cmd.exe");
cmdLine.addArgument("/c");
cmdLine.addArgument("netstat -ano | findstr " + clientPort);
try {
executor.execute(cmdLine);
String result = out.toString();
logger.info(String.format("Find result: %s", result));
if (StringUtils.isNotEmpty(result)) {
String[] values = result.split("\\r\\n");
// values sample:
// Protocol Local address Foreign address Status PID
// TCP 127.0.0.1:2182 127.0.0.1:56672 ESTABLISHED 4020
// TCP 127.0.0.1:56672 127.0.0.1:2182 ESTABLISHED 1980
// TCP 127.0.0.1:56692 127.0.0.1:2182 ESTABLISHED 1980
// TCP 127.0.0.1:56723 127.0.0.1:2182 ESTABLISHED 1980
// TCP [::]:2182 [::]:0 LISTENING 4020
if (values != null && values.length > 0) {
for (int i = 0; i < values.length; i++) {
List<String> segments = Arrays.stream(values[i].trim().split(" "))
.filter(str -> !"".equals(str))
.collect(Collectors.toList());
// segments sample:
// TCP
// 127.0.0.1:2182
// 127.0.0.1:56672
// ESTABLISHED
// 4020
if (segments != null && segments.size() == 5) {
if (this.check(segments.get(1), clientPort)) {
int pid = Integer.valueOf(
segments.get(segments.size() - 1).trim());
context.register(clientPort, pid);
return;
}
}
}
}
}
} catch (IOException e) {
throw new DubboTestException(
String.format("Failed to find the PID of zookeeper with port %d", clientPort), e);
}
}
/**
* Checks if segment is valid ip and port pair.
*
* @param segment the segment to check
* @param clientPort the client port of zookeeper instance
* @return {@code true} if segment is valid pair of ip and port, otherwise {@code false}
*/
private boolean check(String segment, int clientPort) {
return ("[::]:" + clientPort).equalsIgnoreCase(segment)
|| ("0.0.0.0:" + clientPort).equalsIgnoreCase(segment)
|| ("127.0.0.1:" + clientPort).equalsIgnoreCase(segment);
}
}
| 7,351 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperUnixProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperContext;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Create {@link Process} to stop zookeeper on Unix OS.
*/
public class StopZookeeperUnixProcessor extends ZookeeperUnixProcessor {
private static final Logger logger = LoggerFactory.getLogger(StopZookeeperUnixProcessor.class);
/**
* The pattern for checking if the zookeeper instance stopped.
*/
private static final Pattern PATTERN_STOPPED = Pattern.compile(".*STOPPED.*");
@Override
protected Process doProcess(ZookeeperContext context, int clientPort) throws DubboTestException {
logger.info(String.format("The zookeeper-%d is stopping...", clientPort));
List<String> commands = new ArrayList<>();
Path zookeeperBin = Paths.get(
context.getSourceFile().getParent().toString(),
String.valueOf(clientPort),
context.getUnpackedDirectory(),
"bin");
commands.add(Paths.get(zookeeperBin.toString(), "zkServer.sh")
.toAbsolutePath()
.toString());
commands.add("stop");
try {
return new ProcessBuilder()
.directory(zookeeperBin.getParent().toFile())
.command(commands)
.inheritIO()
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.start();
} catch (IOException e) {
throw new DubboTestException(String.format("Failed to stop zookeeper-%d", clientPort), e);
}
}
@Override
protected Pattern getPattern() {
return PATTERN_STOPPED;
}
}
| 7,352 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperWindowsProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.Processor;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext;
/**
* Create {@link Process} to stop zookeeper on Windows OS.
*/
public class StopZookeeperWindowsProcessor extends ZookeeperWindowsProcessor {
private static final Logger logger = LoggerFactory.getLogger(StopZookeeperWindowsProcessor.class);
/**
* The {@link Processor} to find the pid of zookeeper instance.
*/
private final Processor findPidProcessor = new FindPidWindowsProcessor();
/**
* The {@link Processor} to kill the pid of zookeeper instance.
*/
private final Processor killPidProcessor = new KillProcessWindowsProcessor();
@Override
protected void doProcess(ZookeeperWindowsContext context) throws DubboTestException {
logger.info("All of zookeeper instances are stopping...");
// find pid and save into global context.
this.findPidProcessor.process(context);
// kill pid of zookeeper instance if exists
this.killPidProcessor.process(context);
// destroy all resources
context.destroy();
}
}
| 7,353 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/ZookeeperWindowsProcessor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.registrycenter.processor;
import org.apache.dubbo.test.check.exception.DubboTestException;
import org.apache.dubbo.test.check.registrycenter.Context;
import org.apache.dubbo.test.check.registrycenter.Processor;
import org.apache.dubbo.test.check.registrycenter.context.ZookeeperWindowsContext;
/**
* The abstract implementation of {@link Processor} is to provide some common methods on Windows OS.
*/
public abstract class ZookeeperWindowsProcessor implements Processor {
@Override
public void process(Context context) throws DubboTestException {
ZookeeperWindowsContext zookeeperWindowsContext = (ZookeeperWindowsContext) context;
this.doProcess(zookeeperWindowsContext);
}
/**
* Use {@link Process} to handle the command.
*
* @param context the global zookeeper context.
* @throws DubboTestException when any exception occurred.
*/
protected abstract void doProcess(ZookeeperWindowsContext context) throws DubboTestException;
}
| 7,354 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check
|
Create_ds/dubbo/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/exception/DubboTestException.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.test.check.exception;
/**
* Define a specified exception when test.
*/
public class DubboTestException extends RuntimeException {
/**
* Constructs a new {@link DubboTestException} with the specified detail message.
*
* @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
public DubboTestException(String message) {
super(message);
}
/**
* Constructs a new {@link DubboTestException} with the specified detail message and cause.
*
* @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
* (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
public DubboTestException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,355 |
0 |
Create_ds/dubbo/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.dependency;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class FileTest {
private static final List<Pattern> ignoredModules = new LinkedList<>();
private static final List<Pattern> ignoredArtifacts = new LinkedList<>();
private static final List<Pattern> ignoredModulesInDubboAll = new LinkedList<>();
static {
ignoredModules.add(Pattern.compile("dubbo-apache-release"));
ignoredModules.add(Pattern.compile("dubbo-build-tools"));
ignoredModules.add(Pattern.compile("dubbo-dependencies-all"));
ignoredModules.add(Pattern.compile("dubbo-parent"));
ignoredModules.add(Pattern.compile("dubbo-core-spi"));
ignoredModules.add(Pattern.compile("dubbo-demo.*"));
ignoredArtifacts.add(Pattern.compile("dubbo-demo.*"));
ignoredArtifacts.add(Pattern.compile("dubbo-test.*"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-bom"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-compiler"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-dependencies.*"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-distribution"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-metadata-processor"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-native.*"));
ignoredModulesInDubboAll.add(Pattern.compile(".*spring-boot.*"));
ignoredModulesInDubboAll.add(Pattern.compile("dubbo-maven-plugin"));
}
@Test
void checkDubboBom() throws DocumentException {
File baseFile = getBaseFile();
List<File> poms = new LinkedList<>();
readPoms(baseFile, poms);
SAXReader reader = new SAXReader();
List<String> artifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
String dubboBomPath = "dubbo-distribution" + File.separator + "dubbo-bom" + File.separator + "pom.xml";
Document dubboBom = reader.read(new File(getBaseFile(), dubboBomPath));
List<String> artifactIdsInDubboBom = dubboBom
.getRootElement()
.element("dependencyManagement")
.element("dependencies")
.elements("dependency")
.stream()
.map(ele -> ele.elementText("artifactId"))
.collect(Collectors.toList());
List<String> expectedArtifactIds = new LinkedList<>(artifactIds);
expectedArtifactIds.removeAll(artifactIdsInDubboBom);
expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
Assertions.assertTrue(
expectedArtifactIds.isEmpty(),
"Newly created modules must be added to dubbo-bom. Found modules: " + expectedArtifactIds);
}
@Test
void checkArtifacts() throws DocumentException, IOException {
File baseFile = getBaseFile();
List<File> poms = new LinkedList<>();
readPoms(baseFile, poms);
SAXReader reader = new SAXReader();
List<String> artifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
List<String> artifactIdsInRoot = IOUtils.readLines(
this.getClass()
.getClassLoader()
.getResource("META-INF/versions/.artifacts")
.openStream(),
StandardCharsets.UTF_8);
artifactIdsInRoot.removeIf(s -> s.startsWith("#"));
List<String> expectedArtifactIds = new LinkedList<>(artifactIds);
expectedArtifactIds.removeAll(artifactIdsInRoot);
expectedArtifactIds.removeIf(artifactId -> ignoredArtifacts.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
Assertions.assertTrue(
expectedArtifactIds.isEmpty(),
"Newly created modules must be added to .artifacts (in project root). Found modules: "
+ expectedArtifactIds);
}
@Test
void checkDubboDependenciesAll() throws DocumentException {
File baseFile = getBaseFile();
List<File> poms = new LinkedList<>();
readPoms(baseFile, poms);
SAXReader reader = new SAXReader();
List<String> artifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.filter(doc -> !Objects.equals("pom", doc.elementText("packaging")))
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
String dubboDependenciesAllPath =
"dubbo-test" + File.separator + "dubbo-dependencies-all" + File.separator + "pom.xml";
Document dubboDependenciesAll = reader.read(new File(getBaseFile(), dubboDependenciesAllPath));
List<String> artifactIdsInDubboDependenciesAll =
dubboDependenciesAll.getRootElement().element("dependencies").elements("dependency").stream()
.map(ele -> ele.elementText("artifactId"))
.collect(Collectors.toList());
List<String> expectedArtifactIds = new LinkedList<>(artifactIds);
expectedArtifactIds.removeAll(artifactIdsInDubboDependenciesAll);
expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
Assertions.assertTrue(
expectedArtifactIds.isEmpty(),
"Newly created modules must be added to dubbo-dependencies-all. Found modules: " + expectedArtifactIds);
}
@Test
void checkDubboAllDependencies() throws DocumentException {
File baseFile = getBaseFile();
List<File> poms = new LinkedList<>();
readPoms(baseFile, poms);
SAXReader reader = new SAXReader();
List<String> artifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
Assertions.assertEquals(poms.size(), artifactIds.size());
List<String> deployedArtifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.filter(doc -> !Objects.equals("pom", doc.elementText("packaging")))
.filter(doc -> Objects.isNull(doc.element("properties"))
|| (!Objects.equals("true", doc.element("properties").elementText("skip_maven_deploy"))
&& !Objects.equals(
"true", doc.element("properties").elementText("maven.deploy.skip"))))
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
String dubboAllPath = "dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml";
Document dubboAll = reader.read(new File(getBaseFile(), dubboAllPath));
List<String> artifactIdsInDubboAll =
dubboAll.getRootElement().element("dependencies").elements("dependency").stream()
.map(ele -> ele.elementText("artifactId"))
.collect(Collectors.toList());
List<String> expectedArtifactIds = new LinkedList<>(deployedArtifactIds);
expectedArtifactIds.removeAll(artifactIdsInDubboAll);
expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
expectedArtifactIds.removeIf(artifactId -> ignoredModulesInDubboAll.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
Assertions.assertTrue(
expectedArtifactIds.isEmpty(),
"Newly created modules must be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all"
+ File.separator + "pom.xml). Found modules: " + expectedArtifactIds);
List<String> unexpectedArtifactIds = new LinkedList<>(artifactIdsInDubboAll);
unexpectedArtifactIds.removeIf(artifactId -> !artifactIds.contains(artifactId));
unexpectedArtifactIds.removeAll(deployedArtifactIds);
Assertions.assertTrue(
unexpectedArtifactIds.isEmpty(),
"Undeploy dependencies should not be added to dubbo-all(dubbo-distribution" + File.separator
+ "dubbo-all" + File.separator + "pom.xml). Found modules: " + unexpectedArtifactIds);
unexpectedArtifactIds = new LinkedList<>();
for (String artifactId : artifactIdsInDubboAll) {
if (!artifactIds.contains(artifactId)) {
continue;
}
if (ignoredModules.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches())) {
unexpectedArtifactIds.add(artifactId);
}
if (ignoredModulesInDubboAll.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches())) {
unexpectedArtifactIds.add(artifactId);
}
}
Assertions.assertTrue(
unexpectedArtifactIds.isEmpty(),
"Unexpected dependencies should not be added to dubbo-all(dubbo-distribution" + File.separator
+ "dubbo-all" + File.separator + "pom.xml). Found modules: " + unexpectedArtifactIds);
}
@Test
void checkDubboAllShade() throws DocumentException {
File baseFile = getBaseFile();
List<File> poms = new LinkedList<>();
readPoms(baseFile, poms);
SAXReader reader = new SAXReader();
List<String> artifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
Assertions.assertEquals(poms.size(), artifactIds.size());
List<String> deployedArtifactIds = poms.stream()
.map(f -> {
try {
return reader.read(f);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
})
.map(Document::getRootElement)
.filter(doc -> Objects.isNull(doc.element("properties"))
|| (!Objects.equals("true", doc.element("properties").elementText("skip_maven_deploy"))
&& !Objects.equals(
"true", doc.element("properties").elementText("maven.deploy.skip"))))
.filter(doc -> !Objects.equals("pom", doc.elementText("packaging")))
.map(doc -> doc.elementText("artifactId"))
.sorted()
.collect(Collectors.toList());
String dubboAllPath = "dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml";
Document dubboAll = reader.read(new File(getBaseFile(), dubboAllPath));
List<String> artifactIdsInDubboAll =
dubboAll.getRootElement().element("build").element("plugins").elements("plugin").stream()
.filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin"))
.map(ele -> ele.element("executions"))
.map(ele -> ele.elements("execution"))
.flatMap(Collection::stream)
.filter(ele -> ele.elementText("phase").equals("package"))
.map(ele -> ele.element("configuration"))
.map(ele -> ele.element("artifactSet"))
.map(ele -> ele.element("includes"))
.map(ele -> ele.elements("include"))
.flatMap(Collection::stream)
.map(Element::getText)
.filter(artifactId -> artifactId.startsWith("org.apache.dubbo:"))
.map(artifactId -> artifactId.substring("org.apache.dubbo:".length()))
.collect(Collectors.toList());
List<String> expectedArtifactIds = new LinkedList<>(deployedArtifactIds);
expectedArtifactIds.removeAll(artifactIdsInDubboAll);
expectedArtifactIds.removeIf(artifactId -> ignoredModules.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
expectedArtifactIds.removeIf(artifactId -> ignoredModulesInDubboAll.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches()));
Assertions.assertTrue(
expectedArtifactIds.isEmpty(),
"Newly created modules must be added to dubbo-all (dubbo-distribution" + File.separator + "dubbo-all"
+ File.separator + "pom.xml in shade plugin). Found modules: " + expectedArtifactIds);
List<String> unexpectedArtifactIds = new LinkedList<>(artifactIdsInDubboAll);
unexpectedArtifactIds.removeIf(artifactId -> !artifactIds.contains(artifactId));
unexpectedArtifactIds.removeAll(deployedArtifactIds);
Assertions.assertTrue(
unexpectedArtifactIds.isEmpty(),
"Undeploy dependencies should not be added to dubbo-all (dubbo-distribution" + File.separator
+ "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: "
+ unexpectedArtifactIds);
unexpectedArtifactIds = new LinkedList<>();
for (String artifactId : artifactIdsInDubboAll) {
if (!artifactIds.contains(artifactId)) {
continue;
}
if (ignoredModules.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches())) {
unexpectedArtifactIds.add(artifactId);
}
if (ignoredModulesInDubboAll.stream()
.anyMatch(pattern -> pattern.matcher(artifactId).matches())) {
unexpectedArtifactIds.add(artifactId);
}
}
Assertions.assertTrue(
unexpectedArtifactIds.isEmpty(),
"Unexpected dependencies should not be added to dubbo-all (dubbo-distribution" + File.separator
+ "dubbo-all" + File.separator + "pom.xml in shade plugin). Found modules: "
+ unexpectedArtifactIds);
}
@Test
void checkDubboAllTransform() throws DocumentException {
File baseFile = getBaseFile();
List<String> spis = new LinkedList<>();
readSPI(baseFile, spis);
String dubboAllPath = "dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml";
SAXReader reader = new SAXReader();
Document dubboAll = reader.read(new File(baseFile, dubboAllPath));
List<String> transformsInDubboAll =
dubboAll.getRootElement().element("build").element("plugins").elements("plugin").stream()
.filter(ele -> ele.elementText("artifactId").equals("maven-shade-plugin"))
.map(ele -> ele.element("executions"))
.map(ele -> ele.elements("execution"))
.flatMap(Collection::stream)
.filter(ele -> ele.elementText("phase").equals("package"))
.map(ele -> ele.element("configuration"))
.map(ele -> ele.element("transformers"))
.map(ele -> ele.elements("transformer"))
.flatMap(Collection::stream)
.map(ele -> ele.elementText("resource"))
.map(String::trim)
.map(resource -> resource.substring(resource.lastIndexOf("/") + 1))
.collect(Collectors.toList());
List<String> expectedSpis = new LinkedList<>(spis);
expectedSpis.removeAll(transformsInDubboAll);
Assertions.assertTrue(
expectedSpis.isEmpty(),
"Newly created SPI interface must be added to dubbo-all(dubbo-distribution" + File.separator
+ "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: "
+ expectedSpis);
List<String> unexpectedSpis = new LinkedList<>(transformsInDubboAll);
unexpectedSpis.removeAll(spis);
Assertions.assertTrue(
unexpectedSpis.isEmpty(),
"Class without `@SPI` declaration should not be added to dubbo-all(dubbo-distribution" + File.separator
+ "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: "
+ unexpectedSpis);
}
@Test
void checkSpiFiles() {
File baseFile = getBaseFile();
List<String> spis = new LinkedList<>();
readSPI(baseFile, spis);
Map<File, String> spiResources = new HashMap<>();
readSPIResource(baseFile, spiResources);
Map<File, String> copyOfSpis = new HashMap<>(spiResources);
copyOfSpis.entrySet().removeIf(entry -> spis.contains(entry.getValue()));
Assertions.assertTrue(
copyOfSpis.isEmpty(),
"Newly created spi profiles must have a valid class declared with `@SPI`. Found spi profiles: "
+ copyOfSpis.keySet());
List<File> unexpectedSpis = new LinkedList<>();
readSPIUnexpectedResource(baseFile, unexpectedSpis);
unexpectedSpis.removeIf(file -> file.getAbsolutePath()
.contains("dubbo-common" + File.separator + "src" + File.separator + "main" + File.separator
+ "resources" + File.separator + "META-INF" + File.separator + "services" + File.separator
+ "org.apache.dubbo.common.extension.LoadingStrategy"));
Assertions.assertTrue(
unexpectedSpis.isEmpty(),
"Dubbo native provided spi profiles must filed in `META-INF" + File.separator + "dubbo" + File.separator
+ "internal`. Please move to proper folder . Found spis: " + unexpectedSpis);
}
private static File getBaseFile() {
File baseFile = new File(new File("").getAbsolutePath());
while (baseFile != null) {
if (new File(baseFile, ".asf.yaml").exists()) {
break;
}
baseFile = baseFile.getParentFile();
}
Assertions.assertNotNull(baseFile, "Can not find base dir");
System.out.println("Found Project Base Path: " + baseFile.getAbsolutePath());
return baseFile;
}
public void readPoms(File path, List<File> poms) {
if (path.isDirectory()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
readPoms(file, poms);
}
}
} else if (path.isFile()) {
if (path.getAbsolutePath().contains("target")) {
return;
}
if (path.getName().equals("pom.xml")) {
poms.add(path);
}
}
}
public void readSPI(File path, List<String> spis) {
if (path.isDirectory()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
readSPI(file, spis);
}
}
} else if (path.isFile()) {
if (path.getAbsolutePath().contains("target")) {
return;
}
if (path.getAbsolutePath().contains("src" + File.separator + "main" + File.separator + "java")) {
String content;
try {
content = FileUtils.readFileToString(path, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (content != null && content.contains("@SPI")) {
String absolutePath = path.getAbsolutePath();
absolutePath = absolutePath.substring(absolutePath.lastIndexOf(
"src" + File.separator + "main" + File.separator + "java" + File.separator)
+ ("src" + File.separator + "main" + File.separator + "java" + File.separator).length());
absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(".java"));
absolutePath = absolutePath.replaceAll(Matcher.quoteReplacement(File.separator), ".");
spis.add(absolutePath);
}
}
}
}
public void readSPIResource(File path, Map<File, String> spis) {
if (path.isDirectory()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
readSPIResource(file, spis);
}
}
} else if (path.isFile()) {
if (path.getAbsolutePath().contains("target")) {
return;
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF" + File.separator + "dubbo" + File.separator + "internal" + File.separator)) {
String absolutePath = path.getAbsolutePath();
absolutePath = absolutePath.substring(absolutePath.lastIndexOf("src" + File.separator + "main"
+ File.separator + "resources" + File.separator + "META-INF" + File.separator + "dubbo"
+ File.separator + "internal" + File.separator)
+ ("src" + File.separator + "main" + File.separator + "resources" + File.separator + "META-INF"
+ File.separator + "dubbo" + File.separator + "internal" + File.separator)
.length());
absolutePath = absolutePath.replaceAll(Matcher.quoteReplacement(File.separator), ".");
spis.put(path, absolutePath);
}
}
}
public void readSPIUnexpectedResource(File path, List<File> spis) {
if (path.isDirectory()) {
File[] files = path.listFiles();
if (files != null) {
for (File file : files) {
readSPIUnexpectedResource(file, spis);
}
}
} else if (path.isFile()) {
if (path.getAbsolutePath().contains("target")) {
return;
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF" + File.separator + "dubbo" + File.separator + "org.apache.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF" + File.separator + "dubbo" + File.separator + "com.alibaba.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF" + File.separator + "services" + File.separator + "org.apache.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF" + File.separator + "services" + File.separator + "com.alibaba.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF.dubbo" + File.separator + "org.apache.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF.dubbo" + File.separator + "com.alibaba.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF.services" + File.separator + "org.apache.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF.services" + File.separator + "com.alibaba.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF.dubbo.internal" + File.separator + "org.apache.dubbo")) {
spis.add(path);
}
if (path.getAbsolutePath()
.contains("src" + File.separator + "main" + File.separator + "resources" + File.separator
+ "META-INF.dubbo.internal" + File.separator + "com.alibaba.dubbo")) {
spis.add(path);
}
}
}
}
| 7,356 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
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.Exchangers;
import org.apache.dubbo.remoting.transport.dispatcher.FakeChannelHandlers;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class HeartbeatHandlerTest {
private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandlerTest.class);
private ExchangeServer server;
private ExchangeClient client;
@AfterEach
public void after() throws Exception {
if (client != null) {
client.close();
client = null;
}
if (server != null) {
server.close();
server = null;
}
FakeChannelHandlers.resetChannelHandlers();
// wait for timer to finish
Thread.sleep(2000);
}
@Test
void testServerHeartbeat() throws Exception {
FakeChannelHandlers.resetChannelHandlers();
URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56780))
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.HEARTBEAT_KEY, 1000);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
System.out.println("Server bind successfully");
FakeChannelHandlers.setTestingChannelHandlers();
serverURL = serverURL.removeParameter(Constants.HEARTBEAT_KEY);
// Let the client not reply to the heartbeat, and turn off automatic reconnect to simulate the client dropped.
serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
serverURL = serverURL.addParameter(Constants.RECONNECT_KEY, false);
serverURL = serverURL.addParameter(Constants.CODEC_KEY, "telnet");
client = Exchangers.connect(serverURL);
disconnect.await();
Assertions.assertTrue(handler.disconnectCount > 0);
System.out.println("disconnect count " + handler.disconnectCount);
}
@Test
void testHeartbeat() throws Exception {
URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56785))
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.HEARTBEAT_KEY, 1000)
.addParameter(Constants.CODEC_KEY, "telnet");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
System.out.println("Server bind successfully");
client = Exchangers.connect(serverURL);
connect.await();
System.err.println("++++++++++++++ disconnect count " + handler.disconnectCount);
System.err.println("++++++++++++++ connect count " + handler.connectCount);
Assertions.assertEquals(0, handler.disconnectCount);
Assertions.assertEquals(1, handler.connectCount);
}
@Test
void testClientHeartbeat() throws Exception {
FakeChannelHandlers.setTestingChannelHandlers();
URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56790))
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.CODEC_KEY, "telnet");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
System.out.println("Server bind successfully");
FakeChannelHandlers.resetChannelHandlers();
serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000);
client = Exchangers.connect(serverURL);
connect.await();
Assertions.assertTrue(handler.connectCount > 0);
System.out.println("connect count " + handler.connectCount);
}
class TestHeartbeatHandler implements ExchangeHandler {
public int disconnectCount = 0;
public int connectCount = 0;
private CountDownLatch connectCountDownLatch;
private CountDownLatch disconnectCountDownLatch;
public TestHeartbeatHandler(CountDownLatch connectCountDownLatch, CountDownLatch disconnectCountDownLatch) {
this.connectCountDownLatch = connectCountDownLatch;
this.disconnectCountDownLatch = disconnectCountDownLatch;
}
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
return CompletableFuture.completedFuture(request);
}
@Override
public void connected(Channel channel) throws RemotingException {
++connectCount;
connectCountDownLatch.countDown();
}
@Override
public void disconnected(Channel channel) throws RemotingException {
++disconnectCount;
disconnectCountDownLatch.countDown();
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {}
@Override
public void received(Channel channel, Object message) throws RemotingException {
logger.error(this.getClass().getSimpleName() + message.toString());
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
exception.printStackTrace();
}
public String telnet(Channel channel, String message) throws RemotingException {
return message;
}
}
}
| 7,357 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
public class FakeChannelHandlers extends ChannelHandlers {
public FakeChannelHandlers() {
super();
}
public static void setTestingChannelHandlers() {
ChannelHandlers.setTestingChannelHandlers(new FakeChannelHandlers());
}
public static void resetChannelHandlers() {
ChannelHandlers.setTestingChannelHandlers(new ChannelHandlers());
}
@Override
protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) {
return ExtensionLoader.getExtensionLoader(Dispatcher.class)
.getAdaptiveExtension()
.dispatch(handler, url);
}
}
| 7,358 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.Replier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* NettyClientToServerTest
*/
class NettyClientToServerTest extends ClientToServerTest {
protected ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
return Exchangers.bind(url, receiver);
}
protected ExchangeChannel newClient(int port) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&timeout=3000&codec=exchange");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
return Exchangers.connect(url);
}
}
| 7,359 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.Transporter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
class ClientsTest {
@Test
void testGetTransportEmpty() {
try {
ExtensionLoader.getExtensionLoader(Transporter.class).getExtension("");
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void testGetTransportNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
String name = null;
ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name);
});
}
@Test
void testGetTransport3() {
String name = "netty3";
assertEquals(
NettyTransporter.class,
ExtensionLoader.getExtensionLoader(Transporter.class)
.getExtension(name)
.getClass());
}
@Test
void testGetTransportWrong() {
Assertions.assertThrows(IllegalStateException.class, () -> {
String name = "nety";
assertNull(ExtensionLoader.getExtensionLoader(Transporter.class)
.getExtension(name)
.getClass());
});
}
}
| 7,360 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.DubboAppender;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION_KEY;
/**
* Client reconnect test
*/
class ClientReconnectTest {
@BeforeEach
public void clear() {
DubboAppender.clear();
}
@Test
void testReconnect() throws RemotingException, InterruptedException {
{
int port = NetUtils.getAvailablePort();
Client client = startClient(port, 200);
Assertions.assertFalse(client.isConnected());
RemotingServer server = startServer(port);
for (int i = 0; i < 1000 && !client.isConnected(); i++) {
Thread.sleep(10);
}
Assertions.assertTrue(client.isConnected());
client.close(2000);
server.close(2000);
}
{
int port = NetUtils.getAvailablePort();
Client client = startClient(port, 20000);
Assertions.assertFalse(client.isConnected());
RemotingServer server = startServer(port);
for (int i = 0; i < 5; i++) {
Thread.sleep(200);
}
Assertions.assertFalse(client.isConnected());
client.close(2000);
server.close(2000);
}
}
public Client startClient(int port, int heartbeat) throws RemotingException {
URL url = URL.valueOf(
"exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&codec=exchange&client=netty3&"
+ Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
return Exchangers.connect(url);
}
public RemotingServer startServer(int port) throws RemotingException {
final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?server=netty3";
return Exchangers.bind(url, new HandlerAdapter());
}
static class HandlerAdapter extends ExchangeHandlerAdapter {
public HandlerAdapter() {
super(FrameworkModel.defaultModel());
}
@Override
public void connected(Channel channel) throws RemotingException {}
@Override
public void disconnected(Channel channel) throws RemotingException {}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {}
}
}
| 7,361 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.support.Replier;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* ClientToServer
*/
public abstract class ClientToServerTest {
protected static final String LOCALHOST = "127.0.0.1";
protected ExchangeServer server;
protected ExchangeChannel client;
protected WorldHandler handler = new WorldHandler();
protected abstract ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException;
protected abstract ExchangeChannel newClient(int port) throws RemotingException;
@BeforeEach
protected void setUp() throws Exception {
int port = NetUtils.getAvailablePort();
server = newServer(port, handler);
client = newClient(port);
}
@BeforeEach
protected void tearDown() {
try {
if (server != null) server.close();
} finally {
if (client != null) client.close();
}
}
@Test
void testFuture() throws Exception {
CompletableFuture<Object> future = client.request(new World("world"));
Hello result = (Hello) future.get();
Assertions.assertEquals("hello,world", result.getName());
}
// @Test
// public void testCallback() throws Exception {
// final Object waitter = new Object();
// client.invoke(new World("world"), new InvokeCallback<Hello>() {
// public void callback(Hello result) {
// Assertions.assertEquals("hello,world", result.getName());
// synchronized (waitter) {
// waitter.notifyAll();
// }
// }
// public void onException(Throwable exception) {
// }
// });
// synchronized (waitter) {
// waitter.wait();
// }
// }
}
| 7,362 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import java.io.Serializable;
/**
* Data
*/
public class World implements Serializable {
private static final long serialVersionUID = 8563900571013747774L;
private String name;
public World() {}
public World(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 7,363 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* Date: 5/3/11
* Time: 5:47 PM
*/
class NettyClientTest {
static RemotingServer server;
static int port = NetUtils.getAvailablePort();
@BeforeAll
public static void setUp() throws Exception {
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
server = Exchangers.bind(url, new TelnetServerHandler());
}
@AfterAll
public static void tearDown() {
try {
if (server != null) server.close();
} finally {
}
}
// public static void main(String[] args) throws RemotingException, InterruptedException {
// ExchangeChannel client =
// Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty3&heartbeat=1000&codec=exchange"));
// Thread.sleep(60 * 1000 * 50);
// }
@Test
void testClientClose() throws Exception {
List<ExchangeChannel> clients = new ArrayList<ExchangeChannel>(100);
for (int i = 0; i < 100; i++) {
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&codec=exchange");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
ExchangeChannel client = Exchangers.connect(url);
Thread.sleep(5);
clients.add(client);
}
for (ExchangeChannel client : clients) {
client.close();
}
Thread.sleep(1000);
}
@Test
void testServerClose() throws Exception {
for (int i = 0; i < 100; i++) {
URL url = URL.valueOf(
"exchange://localhost:" + NetUtils.getAvailablePort(6000) + "?server=netty3&codec=exchange");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
RemotingServer aServer = Exchangers.bind(url, new TelnetServerHandler());
aServer.close();
}
}
}
| 7,364 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import java.io.Serializable;
/**
* Result
*/
public class Hello implements Serializable {
private static final long serialVersionUID = 8563900571013747774L;
private String name;
public Hello() {}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 7,365 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class ThreadNameTest {
private NettyServer server;
private NettyClient client;
private URL serverURL;
private URL clientURL;
private ThreadNameVerifyHandler serverHandler;
private ThreadNameVerifyHandler clientHandler;
private static String serverRegex = "DubboServerHandler\\-localhost:(\\d+)\\-thread\\-(\\d+)";
private static String clientRegex = "DubboClientHandler\\-thread\\-(\\d+)";
private final CountDownLatch serverLatch = new CountDownLatch(1);
private final CountDownLatch clientLatch = new CountDownLatch(1);
@BeforeEach
public void before() throws Exception {
int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000));
serverURL = URL.valueOf("telnet://localhost?side=provider&codec=telnet").setPort(port);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
clientURL = URL.valueOf("telnet://localhost?side=consumer&codec=telnet").setPort(port);
clientURL = clientURL.setScopeModel(applicationModel);
serverHandler = new ThreadNameVerifyHandler(serverRegex, false, serverLatch);
clientHandler = new ThreadNameVerifyHandler(clientRegex, true, clientLatch);
server = new NettyServer(serverURL, serverHandler);
client = new NettyClient(clientURL, clientHandler);
}
@AfterEach
public void after() throws Exception {
if (client != null) {
client.close();
client = null;
}
if (server != null) {
server.close();
server = null;
}
}
@Test
void testThreadName() throws Exception {
client.send("hello");
serverLatch.await(30, TimeUnit.SECONDS);
clientLatch.await(30, TimeUnit.SECONDS);
if (!serverHandler.isSuccess() || !clientHandler.isSuccess()) {
Assertions.fail();
}
}
class ThreadNameVerifyHandler implements ChannelHandler {
private String message;
private boolean success;
private boolean client;
private CountDownLatch latch;
ThreadNameVerifyHandler(String msg, boolean client, CountDownLatch latch) {
message = msg;
this.client = client;
this.latch = latch;
}
public boolean isSuccess() {
return success;
}
private void checkThreadName() {
if (!success) {
success = Thread.currentThread().getName().matches(message);
}
if (success) {
latch.countDown();
}
}
private void output(String method) {
System.out.println(
Thread.currentThread().getName() + " " + (client ? "client " + method : "server " + method));
}
@Override
public void connected(Channel channel) throws RemotingException {
output("connected");
checkThreadName();
}
@Override
public void disconnected(Channel channel) throws RemotingException {
// client: DubboClientHandler thread, server: DubboServerHandler or DubboSharedHandler thread.
output("disconnected");
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {
// main thread.
output("sent");
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
// server: DubboServerHandler or DubboSharedHandler thread.
output("received");
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
// client: DubboClientHandler thread, server: ?
output("caught");
}
}
}
| 7,366 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* DataHandler
*/
public class WorldHandler implements Replier<World> {
public Class<World> interest() {
return World.class;
}
public Object reply(ExchangeChannel channel, World msg) throws RemotingException {
return new Hello("hello," + msg.getName());
}
}
| 7,367 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* Date: 4/26/11
* Time: 4:13 PM
*/
class NettyStringTest {
static ExchangeServer server;
static ExchangeChannel client;
@BeforeAll
public static void setUp() throws Exception {
// int port = (int) (1000 * Math.random() + 10000);
// int port = 10001;
int port = NetUtils.getAvailablePort();
System.out.println(port);
URL serverURL = URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty3&codec=telnet");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
URL clientURL = URL.valueOf("telnet://127.0.0.1:" + port + "?client=netty3&codec=telnet");
clientURL = clientURL.setScopeModel(applicationModel);
server = Exchangers.bind(serverURL, new TelnetServerHandler());
client = Exchangers.connect(clientURL, new TelnetClientHandler());
}
@AfterAll
public static void tearDown() {
try {
if (server != null) server.close();
} finally {
if (client != null) client.close();
}
}
@Test
void testHandler() {
// Thread.sleep(20000);
/*client.request("world\r\n");
Future future = client.request("world", 10000);
String result = (String)future.get();
Assertions.assertEquals("Did you say 'world'?\r\n",result);*/
}
}
| 7,368 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetClientHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* Date: 4/28/11
* Time: 11:15 AM
*/
public class TelnetClientHandler implements Replier<String> {
public Class<String> interest() {
return String.class;
}
public Object reply(ExchangeChannel channel, String msg) throws RemotingException {
return msg;
}
}
| 7,369 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* Date: 4/26/11
* Time: 4:29 PM
*/
public class TelnetServerHandler implements Replier<String> {
public Class<String> interest() {
return String.class;
}
public Object reply(ExchangeChannel channel, String msg) throws RemotingException {
// Generate and write a response.
String response;
if (msg.length() == 0) {
response = "Please type something.\r\n";
} else {
response = "Did you say '" + msg + "'?\r\n";
}
// System.out.println(response);
return response;
}
}
| 7,370 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class NettyBackedChannelBufferTest {
private static final int CAPACITY = 4096;
private ChannelBuffer buffer;
@BeforeEach
public void init() {
buffer = new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(CAPACITY));
}
@AfterEach
public void dispose() {
buffer = null;
}
@Test
void testBufferTransfer() {
byte[] tmp1 = {1, 2};
byte[] tmp2 = {3, 4};
ChannelBuffer source = new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(2));
source.writeBytes(tmp1);
buffer.writeBytes(tmp2);
assertEquals(2, buffer.readableBytes());
source.setBytes(0, tmp1, 0, 2);
buffer.setBytes(0, source, 0, 2);
assertEquals(2, buffer.readableBytes());
byte[] actual = new byte[2];
buffer.getBytes(0, actual);
assertEquals(1, actual[0]);
assertEquals(2, actual[1]);
}
}
| 7,371 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient;
import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer;
import org.apache.dubbo.remoting.api.pu.PortUnificationTransporter;
public class NettyPortUnificationTransporter implements PortUnificationTransporter {
public static final String NAME = "netty3";
@Override
public AbstractPortUnificationServer bind(URL url, ChannelHandler handler) throws RemotingException {
return new NettyPortUnificationServer(url, handler);
}
@Override
public AbstractConnectionClient connect(URL url, ChannelHandler handler) throws RemotingException {
throw new RemotingException(url.toInetSocketAddress(), null, "connectionManager for netty3 spi not found.");
}
}
| 7,372 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyClient.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.transport.AbstractClient;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_CLIENT_CONNECT_TIMEOUT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CONNECT_PROVIDER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DISCONNECT_PROVIDER;
/**
* NettyClient.
*/
public class NettyClient extends AbstractClient {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyClient.class);
// ChannelFactory's closure has a DirectMemory leak, using static to avoid
// https://issues.jboss.org/browse/NETTY-424
private static final ChannelFactory CHANNEL_FACTORY = new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)),
Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)),
Constants.DEFAULT_IO_THREADS);
private ClientBootstrap bootstrap;
private volatile Channel channel; // volatile, please copy reference to use
public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException {
super(url, wrapChannelHandler(url, handler));
}
@Override
protected void doOpen() throws Throwable {
NettyHelper.setNettyLoggerFactory();
bootstrap = new ClientBootstrap(CHANNEL_FACTORY);
// config
// @see org.jboss.netty.channel.socket.SocketChannelConfig
bootstrap.setOption("keepAlive", true);
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() {
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", adapter.getDecoder());
pipeline.addLast("encoder", adapter.getEncoder());
pipeline.addLast("handler", nettyHandler);
return pipeline;
}
});
}
@Override
protected void doConnect() throws Throwable {
long start = System.currentTimeMillis();
ChannelFuture future = bootstrap.connect(getConnectAddress());
try {
boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.getChannel();
newChannel.setInterestOps(Channel.OP_READ_WRITE);
try {
// Close old channel
Channel oldChannel = NettyClient.this.channel; // copy reference
if (oldChannel != null) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close old netty channel " + oldChannel + " on create new netty channel "
+ newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
}
}
} else if (future.getCause() != null) {
Throwable cause = future.getCause();
RemotingException remotingException = new RemotingException(
this,
"client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress()
+ ", error message is:" + cause.getMessage(),
cause);
// 6-1 - Failed to connect to provider server by other reason.
logger.error(
TRANSPORT_FAILED_CONNECT_PROVIDER,
"network disconnected",
"",
"Failed to connect to provider server by other reason.",
cause);
throw remotingException;
} else {
RemotingException remotingException = new RemotingException(
this,
"client(url: " + getUrl() + ") failed to connect to server "
+ getRemoteAddress() + " client-side timeout "
+ getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start)
+ "ms) from netty client "
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
// 6-2 - Client-side timeout.
logger.error(
TRANSPORT_CLIENT_CONNECT_TIMEOUT,
"provider crash",
"",
"Client-side timeout.",
remotingException);
throw remotingException;
}
} finally {
if (!isConnected()) {
future.cancel();
}
}
}
@Override
protected void doDisConnect() throws Throwable {
try {
NettyChannel.removeChannelIfDisconnected(channel);
} catch (Throwable t) {
logger.warn(TRANSPORT_FAILED_DISCONNECT_PROVIDER, "", "", t.getMessage());
}
}
@Override
protected void doClose() throws Throwable {
/*try {
bootstrap.releaseExternalResources();
} catch (Throwable t) {
logger.warn(t.getMessage());
}*/
}
@Override
protected org.apache.dubbo.remoting.Channel getChannel() {
Channel c = channel;
if (c == null || !c.isConnected()) {
return null;
}
return NettyChannel.getOrAddChannel(c, getUrl(), this);
}
Channel getNettyChannel() {
return channel;
}
}
| 7,373 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyTransporter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
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;
public class NettyTransporter implements Transporter {
public static final String NAME = "netty3";
@Override
public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException {
return new NettyServer(url, handler);
}
@Override
public Client connect(URL url, ChannelHandler handler) throws RemotingException {
return new NettyClient(url, handler);
}
}
| 7,374 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHelper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.jboss.netty.logging.AbstractInternalLogger;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
final class NettyHelper {
public static void setNettyLoggerFactory() {
InternalLoggerFactory factory = InternalLoggerFactory.getDefaultFactory();
if (!(factory instanceof DubboLoggerFactory)) {
InternalLoggerFactory.setDefaultFactory(new DubboLoggerFactory());
}
}
static class DubboLoggerFactory extends InternalLoggerFactory {
@Override
public InternalLogger newInstance(String name) {
return new DubboLogger(LoggerFactory.getErrorTypeAwareLogger(name));
}
}
static class DubboLogger extends AbstractInternalLogger {
public static final String LOGGER_CAUSE_STRING = "unknown error in remoting-netty module";
private ErrorTypeAwareLogger logger;
DubboLogger(ErrorTypeAwareLogger logger) {
this.logger = logger;
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override
public void debug(String msg) {
logger.debug(msg);
}
@Override
public void debug(String msg, Throwable cause) {
logger.debug(msg, cause);
}
@Override
public void info(String msg) {
logger.info(msg);
}
@Override
public void info(String msg, Throwable cause) {
logger.info(msg, cause);
}
@Override
public void warn(String msg) {
logger.warn(INTERNAL_ERROR, LOGGER_CAUSE_STRING, "", msg);
}
@Override
public void warn(String msg, Throwable cause) {
logger.warn(INTERNAL_ERROR, LOGGER_CAUSE_STRING, "", msg, cause);
}
@Override
public void error(String msg) {
logger.error(INTERNAL_ERROR, LOGGER_CAUSE_STRING, "", msg);
}
@Override
public void error(String msg, Throwable cause) {
logger.error(INTERNAL_ERROR, LOGGER_CAUSE_STRING, "", msg, cause);
}
@Override
public String toString() {
return logger.toString();
}
}
}
| 7,375 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
/**
* NettyHandler
*/
@Sharable
public class NettyHandler extends SimpleChannelHandler {
private static final Logger logger = LoggerFactory.getLogger(NettyHandler.class);
private final Map<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); // <ip:port, channel>
private final URL url;
private final ChannelHandler handler;
public NettyHandler(URL url, ChannelHandler handler) {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
this.url = url;
this.handler = handler;
}
public Map<String, Channel> getChannels() {
return channels;
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
if (channel != null) {
channels.put(
NetUtils.toAddressString(
(InetSocketAddress) ctx.getChannel().getRemoteAddress()),
channel);
}
handler.connected(channel);
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
if (logger.isInfoEnabled()) {
logger.info("The connection between " + channel.getRemoteAddress() + " and " + channel.getLocalAddress()
+ " is established");
}
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
channels.remove(NetUtils.toAddressString(
(InetSocketAddress) ctx.getChannel().getRemoteAddress()));
handler.disconnected(channel);
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
if (logger.isInfoEnabled()) {
logger.info("The connection between " + channel.getRemoteAddress() + " and " + channel.getLocalAddress()
+ " is disconnected");
}
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
handler.received(channel, e.getMessage());
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
super.writeRequested(ctx, e);
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
handler.sent(channel, e.getMessage());
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
handler.caught(channel, e.getCause());
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
}
| 7,376 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME;
/**
* NettyServer
*/
public class NettyPortUnificationServer extends AbstractPortUnificationServer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(NettyPortUnificationServer.class);
private Map<String, Channel> dubboChannels = new ConcurrentHashMap<>(); // <ip:port, channel>
private ServerBootstrap bootstrap;
private org.jboss.netty.channel.Channel channel;
public NettyPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, ChannelHandlers.wrap(handler, url));
}
@Override
public void addSupportedProtocol(URL url, ChannelHandler handler) {
super.addSupportedProtocol(url, ChannelHandlers.wrap(handler, url));
}
@Override
public void close() {
if (channel != null) {
doClose();
}
}
public void bind() {
if (channel == null) {
doOpen();
}
}
@Override
protected void doOpen() {
NettyHelper.setNettyLoggerFactory();
ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_BOSS_POOL_NAME, true));
ExecutorService worker =
Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true));
ChannelFactory channelFactory = new NioServerSocketChannelFactory(
boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
bootstrap = new ServerBootstrap(channelFactory);
final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
dubboChannels = nettyHandler.getChannels();
// https://issues.jboss.org/browse/NETTY-365
// https://issues.jboss.org/browse/NETTY-379
// final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("backlog", getUrl().getPositiveParameter(BACKLOG_KEY, Constants.DEFAULT_BACKLOG));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() {
NettyCodecAdapter adapter =
new NettyCodecAdapter(getCodec(), getUrl(), NettyPortUnificationServer.this);
ChannelPipeline pipeline = Channels.pipeline();
/*int idleTimeout = getIdleTimeout();
if (idleTimeout > 10000) {
pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
}*/
pipeline.addLast("decoder", adapter.getDecoder());
pipeline.addLast("encoder", adapter.getEncoder());
pipeline.addLast("handler", nettyHandler);
return pipeline;
}
});
// bind
String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost());
int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort());
if (getUrl().getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) {
bindIp = ANYHOST_VALUE;
}
InetSocketAddress bindAddress = new InetSocketAddress(bindIp, bindPort);
channel = bootstrap.bind(bindAddress);
}
@Override
protected void doClose() {
try {
if (channel != null) {
// unbind.
channel.close();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
Collection<Channel> channels = getChannels();
if (CollectionUtils.isNotEmpty(channels)) {
for (Channel channel : channels) {
try {
channel.close();
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
for (WireProtocol protocol : getProtocols()) {
protocol.close();
}
try {
if (bootstrap != null) {
// release external resource.
bootstrap.releaseExternalResources();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
if (dubboChannels != null) {
dubboChannels.clear();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
@Override
protected int getChannelsSize() {
return dubboChannels.size();
}
@Override
public Collection<Channel> getChannels() {
Collection<Channel> chs = new ArrayList<>(this.dubboChannels.size());
chs.addAll(this.dubboChannels.values());
return chs;
}
@Override
public Channel getChannel(InetSocketAddress remoteAddress) {
return dubboChannels.get(NetUtils.toAddressString(remoteAddress));
}
public InetSocketAddress getLocalAddress() {
return (InetSocketAddress) channel.getLocalAddress();
}
@Override
public boolean isBound() {
return channel.isBound();
}
}
| 7,377 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer;
import java.io.IOException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import static org.apache.dubbo.remoting.Constants.BUFFER_KEY;
import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE;
import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE;
import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE;
/**
* NettyCodecAdapter.
*/
final class NettyCodecAdapter {
private final ChannelHandler encoder = new InternalEncoder();
private final ChannelHandler decoder = new InternalDecoder();
private final Codec2 codec;
private final URL url;
private final int bufferSize;
private final org.apache.dubbo.remoting.ChannelHandler handler;
public NettyCodecAdapter(Codec2 codec, URL url, org.apache.dubbo.remoting.ChannelHandler handler) {
this.codec = codec;
this.url = url;
this.handler = handler;
int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE);
this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE;
}
public ChannelHandler getEncoder() {
return encoder;
}
public ChannelHandler getDecoder() {
return decoder;
}
@Sharable
private class InternalEncoder extends OneToOneEncoder {
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
org.apache.dubbo.remoting.buffer.ChannelBuffer buffer =
org.apache.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
try {
codec.encode(channel, buffer, msg);
} finally {
NettyChannel.removeChannelIfDisconnected(ch);
}
return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
}
private class InternalDecoder extends SimpleChannelUpstreamHandler {
private org.apache.dubbo.remoting.buffer.ChannelBuffer buffer =
org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
Object o = event.getMessage();
if (!(o instanceof ChannelBuffer)) {
ctx.sendUpstream(event);
return;
}
ChannelBuffer input = (ChannelBuffer) o;
int readable = input.readableBytes();
if (readable <= 0) {
return;
}
org.apache.dubbo.remoting.buffer.ChannelBuffer message;
if (buffer.readable()) {
if (buffer instanceof DynamicChannelBuffer) {
buffer.writeBytes(input.toByteBuffer());
message = buffer;
} else {
int size = buffer.readableBytes() + input.readableBytes();
message = org.apache.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(
size > bufferSize ? size : bufferSize);
message.writeBytes(buffer, buffer.readableBytes());
message.writeBytes(input.toByteBuffer());
}
} else {
message = org.apache.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer(input.toByteBuffer());
}
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
Object msg;
int saveReaderIndex;
try {
// decode object.
do {
saveReaderIndex = message.readerIndex();
try {
msg = codec.decode(channel, message);
} catch (IOException e) {
buffer = org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
throw e;
}
if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) {
message.readerIndex(saveReaderIndex);
break;
} else {
if (saveReaderIndex == message.readerIndex()) {
buffer = org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
throw new IOException("Decode without read data.");
}
if (msg != null) {
Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress());
}
}
} while (message.readable());
} finally {
if (message.readable()) {
message.discardReadBytes();
buffer = message;
} else {
buffer = org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
}
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
ctx.sendUpstream(e);
}
}
}
| 7,378 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBufferFactory;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public class NettyBackedChannelBuffer implements ChannelBuffer {
private final org.jboss.netty.buffer.ChannelBuffer buffer;
public NettyBackedChannelBuffer(org.jboss.netty.buffer.ChannelBuffer buffer) {
Assert.notNull(buffer, "buffer == null");
this.buffer = buffer;
}
public org.jboss.netty.buffer.ChannelBuffer nettyChannelBuffer() {
return buffer;
}
@Override
public int capacity() {
return buffer.capacity();
}
@Override
public ChannelBuffer copy(int index, int length) {
return new NettyBackedChannelBuffer(buffer.copy(index, length));
}
@Override
public ChannelBufferFactory factory() {
return NettyBackedChannelBufferFactory.getInstance();
}
@Override
public byte getByte(int index) {
return buffer.getByte(index);
}
@Override
public void getBytes(int index, byte[] dst, int dstIndex, int length) {
buffer.getBytes(index, dst, dstIndex, length);
}
@Override
public void getBytes(int index, ByteBuffer dst) {
buffer.getBytes(index, dst);
}
@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
// careful
byte[] data = new byte[length];
buffer.getBytes(index, data, 0, length);
dst.setBytes(dstIndex, data, 0, length);
}
@Override
public void getBytes(int index, OutputStream dst, int length) throws IOException {
buffer.getBytes(index, dst, length);
}
@Override
public boolean isDirect() {
return buffer.isDirect();
}
@Override
public void setByte(int index, int value) {
buffer.setByte(index, value);
}
@Override
public void setBytes(int index, byte[] src, int srcIndex, int length) {
buffer.setBytes(index, src, srcIndex, length);
}
@Override
public void setBytes(int index, ByteBuffer src) {
buffer.setBytes(index, src);
}
@Override
public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) {
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
// careful
byte[] data = new byte[length];
src.getBytes(srcIndex, data, 0, length);
setBytes(index, data, 0, length);
}
@Override
public int setBytes(int index, InputStream src, int length) throws IOException {
return buffer.setBytes(index, src, length);
}
@Override
public ByteBuffer toByteBuffer(int index, int length) {
return buffer.toByteBuffer(index, length);
}
@Override
public byte[] array() {
return buffer.array();
}
@Override
public boolean hasArray() {
return buffer.hasArray();
}
@Override
public int arrayOffset() {
return buffer.arrayOffset();
}
// AbstractChannelBuffer
@Override
public void clear() {
buffer.clear();
}
@Override
public ChannelBuffer copy() {
return new NettyBackedChannelBuffer(buffer.copy());
}
@Override
public void discardReadBytes() {
buffer.discardReadBytes();
}
@Override
public void ensureWritableBytes(int writableBytes) {
buffer.ensureWritableBytes(writableBytes);
}
@Override
public void getBytes(int index, byte[] dst) {
buffer.getBytes(index, dst);
}
@Override
public void getBytes(int index, ChannelBuffer dst) {
// careful
getBytes(index, dst, dst.writableBytes());
}
@Override
public void getBytes(int index, ChannelBuffer dst, int length) {
// careful
if (length > dst.writableBytes()) {
throw new IndexOutOfBoundsException();
}
getBytes(index, dst, dst.writerIndex(), length);
dst.writerIndex(dst.writerIndex() + length);
}
@Override
public void markReaderIndex() {
buffer.markReaderIndex();
}
@Override
public void markWriterIndex() {
buffer.markWriterIndex();
}
@Override
public boolean readable() {
return buffer.readable();
}
@Override
public int readableBytes() {
return buffer.readableBytes();
}
@Override
public byte readByte() {
return buffer.readByte();
}
@Override
public void readBytes(byte[] dst) {
buffer.readBytes(dst);
}
@Override
public void readBytes(byte[] dst, int dstIndex, int length) {
buffer.readBytes(dst, dstIndex, length);
}
@Override
public void readBytes(ByteBuffer dst) {
buffer.readBytes(dst);
}
@Override
public void readBytes(ChannelBuffer dst) {
// careful
readBytes(dst, dst.writableBytes());
}
@Override
public void readBytes(ChannelBuffer dst, int length) {
// careful
if (length > dst.writableBytes()) {
throw new IndexOutOfBoundsException();
}
readBytes(dst, dst.writerIndex(), length);
dst.writerIndex(dst.writerIndex() + length);
}
@Override
public void readBytes(ChannelBuffer dst, int dstIndex, int length) {
// careful
if (readableBytes() < length) {
throw new IndexOutOfBoundsException();
}
byte[] data = new byte[length];
buffer.readBytes(data, 0, length);
dst.setBytes(dstIndex, data, 0, length);
}
@Override
public ChannelBuffer readBytes(int length) {
return new NettyBackedChannelBuffer(buffer.readBytes(length));
}
@Override
public void resetReaderIndex() {
buffer.resetReaderIndex();
}
@Override
public void resetWriterIndex() {
buffer.resetWriterIndex();
}
@Override
public int readerIndex() {
return buffer.readerIndex();
}
@Override
public void readerIndex(int readerIndex) {
buffer.readerIndex(readerIndex);
}
@Override
public void readBytes(OutputStream dst, int length) throws IOException {
buffer.readBytes(dst, length);
}
@Override
public void setBytes(int index, byte[] src) {
buffer.setBytes(index, src);
}
@Override
public void setBytes(int index, ChannelBuffer src) {
// careful
setBytes(index, src, src.readableBytes());
}
@Override
public void setBytes(int index, ChannelBuffer src, int length) {
// careful
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
setBytes(index, src, src.readerIndex(), length);
src.readerIndex(src.readerIndex() + length);
}
@Override
public void setIndex(int readerIndex, int writerIndex) {
buffer.setIndex(readerIndex, writerIndex);
}
@Override
public void skipBytes(int length) {
buffer.skipBytes(length);
}
@Override
public ByteBuffer toByteBuffer() {
return buffer.toByteBuffer();
}
@Override
public boolean writable() {
return buffer.writable();
}
@Override
public int writableBytes() {
return buffer.writableBytes();
}
@Override
public void writeByte(int value) {
buffer.writeByte(value);
}
@Override
public void writeBytes(byte[] src) {
buffer.writeBytes(src);
}
@Override
public void writeBytes(byte[] src, int index, int length) {
buffer.writeBytes(src, index, length);
}
@Override
public void writeBytes(ByteBuffer src) {
buffer.writeBytes(src);
}
@Override
public void writeBytes(ChannelBuffer src) {
// careful
writeBytes(src, src.readableBytes());
}
@Override
public void writeBytes(ChannelBuffer src, int length) {
// careful
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
writeBytes(src, src.readerIndex(), length);
src.readerIndex(src.readerIndex() + length);
}
@Override
public void writeBytes(ChannelBuffer src, int srcIndex, int length) {
// careful
byte[] data = new byte[length];
src.getBytes(srcIndex, data, 0, length);
writeBytes(data, 0, length);
}
@Override
public int writeBytes(InputStream src, int length) throws IOException {
return buffer.writeBytes(src, length);
}
@Override
public int writerIndex() {
return buffer.writerIndex();
}
@Override
public void writerIndex(int writerIndex) {
buffer.writerIndex(writerIndex);
}
@Override
public int compareTo(ChannelBuffer o) {
return ChannelBuffers.compare(this, o);
}
}
| 7,379 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBufferFactory;
import java.nio.ByteBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
/**
* Wrap netty dynamic channel buffer.
*/
public class NettyBackedChannelBufferFactory implements ChannelBufferFactory {
private static final NettyBackedChannelBufferFactory INSTANCE = new NettyBackedChannelBufferFactory();
public static ChannelBufferFactory getInstance() {
return INSTANCE;
}
@Override
public ChannelBuffer getBuffer(int capacity) {
return new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(capacity));
}
@Override
public ChannelBuffer getBuffer(byte[] array, int offset, int length) {
org.jboss.netty.buffer.ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(length);
buffer.writeBytes(array, offset, length);
return new NettyBackedChannelBuffer(buffer);
}
@Override
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
return new NettyBackedChannelBuffer(ChannelBuffers.wrappedBuffer(nioBuffer));
}
}
| 7,380 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyServer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.transport.AbstractServer;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME;
/**
* NettyServer
*/
public class NettyServer extends AbstractServer implements RemotingServer {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyServer.class);
private Map<String, Channel> channels; // <ip:port, channel>
private ServerBootstrap bootstrap;
private org.jboss.netty.channel.Channel channel;
public NettyServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, ChannelHandlers.wrap(handler, url));
}
@Override
protected void doOpen() throws Throwable {
NettyHelper.setNettyLoggerFactory();
ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_BOSS_POOL_NAME, true));
ExecutorService worker =
Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true));
ChannelFactory channelFactory = new NioServerSocketChannelFactory(
boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
bootstrap = new ServerBootstrap(channelFactory);
final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
channels = nettyHandler.getChannels();
// https://issues.jboss.org/browse/NETTY-365
// https://issues.jboss.org/browse/NETTY-379
// final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("backlog", getUrl().getPositiveParameter(BACKLOG_KEY, Constants.DEFAULT_BACKLOG));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() {
NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
ChannelPipeline pipeline = Channels.pipeline();
/*int idleTimeout = getIdleTimeout();
if (idleTimeout > 10000) {
pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
}*/
pipeline.addLast("decoder", adapter.getDecoder());
pipeline.addLast("encoder", adapter.getEncoder());
pipeline.addLast("handler", nettyHandler);
return pipeline;
}
});
// bind
channel = bootstrap.bind(getBindAddress());
}
@Override
protected void doClose() throws Throwable {
try {
if (channel != null) {
// unbind.
channel.close();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
Collection<org.apache.dubbo.remoting.Channel> channels = getChannels();
if (CollectionUtils.isNotEmpty(channels)) {
for (org.apache.dubbo.remoting.Channel channel : channels) {
try {
channel.close();
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
if (bootstrap != null) {
// release external resource.
bootstrap.releaseExternalResources();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
if (channels != null) {
channels.clear();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
@Override
protected int getChannelsSize() {
return channels.size();
}
@Override
public Collection<Channel> getChannels() {
Collection<Channel> chs = new ArrayList<>(this.channels.size());
// pick channels from NettyServerHandler ( needless to check connectivity )
chs.addAll(this.channels.values());
return chs;
}
@Override
public Channel getChannel(InetSocketAddress remoteAddress) {
return channels.get(NetUtils.toAddressString(remoteAddress));
}
@Override
public boolean isBound() {
return channel.isBound();
}
}
| 7,381 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyChannel.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.transport.AbstractChannel;
import org.apache.dubbo.remoting.utils.PayloadDropper;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jboss.netty.channel.ChannelFuture;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE;
/**
* NettyChannel.
*/
final class NettyChannel extends AbstractChannel {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(NettyChannel.class);
private static final ConcurrentMap<org.jboss.netty.channel.Channel, NettyChannel> CHANNEL_MAP =
new ConcurrentHashMap<org.jboss.netty.channel.Channel, NettyChannel>();
private final org.jboss.netty.channel.Channel channel;
private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
private NettyChannel(org.jboss.netty.channel.Channel channel, URL url, ChannelHandler handler) {
super(url, handler);
if (channel == null) {
throw new IllegalArgumentException("netty channel == null;");
}
this.channel = channel;
}
static NettyChannel getOrAddChannel(org.jboss.netty.channel.Channel ch, URL url, ChannelHandler handler) {
if (ch == null) {
return null;
}
NettyChannel ret = CHANNEL_MAP.get(ch);
if (ret == null) {
NettyChannel nc = new NettyChannel(ch, url, handler);
if (ch.isConnected()) {
ret = CHANNEL_MAP.putIfAbsent(ch, nc);
}
if (ret == null) {
ret = nc;
}
}
return ret;
}
static void removeChannelIfDisconnected(org.jboss.netty.channel.Channel ch) {
if (ch != null && !ch.isConnected()) {
CHANNEL_MAP.remove(ch);
}
}
@Override
public InetSocketAddress getLocalAddress() {
return (InetSocketAddress) channel.getLocalAddress();
}
@Override
public InetSocketAddress getRemoteAddress() {
return (InetSocketAddress) channel.getRemoteAddress();
}
@Override
public boolean isConnected() {
return channel.isConnected();
}
@Override
public void send(Object message, boolean sent) throws RemotingException {
super.send(message, sent);
boolean success = true;
int timeout = 0;
try {
ChannelFuture future = channel.write(message);
if (sent) {
timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
success = future.await(timeout);
}
Throwable cause = future.getCause();
if (cause != null) {
throw cause;
}
} catch (Throwable e) {
throw new RemotingException(
this,
"Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to "
+ getRemoteAddress() + ", cause: " + e.getMessage(),
e);
}
if (!success) {
throw new RemotingException(
this,
"Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to "
+ getRemoteAddress() + "in timeout(" + timeout + "ms) limit");
}
}
@Override
public void close() {
try {
super.close();
} catch (Exception e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
removeChannelIfDisconnected(channel);
} catch (Exception e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
attributes.clear();
} catch (Exception e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
if (logger.isInfoEnabled()) {
logger.info("Close netty channel " + channel);
}
channel.close();
} catch (Exception e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
@Override
public boolean hasAttribute(String key) {
return attributes.containsKey(key);
}
@Override
public Object getAttribute(String key) {
return attributes.get(key);
}
@Override
public void setAttribute(String key, Object value) {
if (value == null) { // The null value unallowed in the ConcurrentHashMap.
attributes.remove(key);
} else {
attributes.put(key, value);
}
}
@Override
public void removeAttribute(String key) {
attributes.remove(key);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((channel == null) ? 0 : channel.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
// FIXME: a hack to make org.apache.dubbo.remoting.exchange.support.DefaultFuture.closeChannel work
if (obj instanceof NettyClient) {
NettyClient client = (NettyClient) obj;
return channel.equals(client.getNettyChannel());
}
if (getClass() != obj.getClass()) {
return false;
}
NettyChannel other = (NettyChannel) obj;
if (channel == null) {
if (other.channel != null) {
return false;
}
} else if (!channel.equals(other.channel)) {
return false;
}
return true;
}
@Override
public String toString() {
return "NettyChannel [channel=" + channel + "]";
}
}
| 7,382 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientCloseTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
/**
* ProformanceClient
* The test class will report abnormal thread pool, because the judgment on the thread pool concurrency problems produced in DefaultChannelHandler (connected event has been executed asynchronously, judgment, then closed the thread pool, thread pool and execution error, this problem can be specified through the Constants.CHANNEL_HANDLER_KEY=connection.)
*/
class PerformanceClientCloseTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceClientCloseTest.class);
@Test
void testClient() throws Throwable {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
final int concurrent = PerformanceUtils.getIntProperty("concurrent", 1);
final int runs = PerformanceUtils.getIntProperty("runs", Integer.MAX_VALUE);
final String onerror = PerformanceUtils.getProperty("onerror", "continue");
final String url = "exchange://" + server + "?transporter=" + transporter
+ "&serialization=" + serialization
// + "&"+Constants.CHANNEL_HANDLER_KEY+"=connection"
+ "&timeout=" + timeout;
final AtomicInteger count = new AtomicInteger();
final AtomicInteger error = new AtomicInteger();
for (int n = 0; n < concurrent; n++) {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < runs; i++) {
ExchangeClient client = null;
try {
client = Exchangers.connect(url);
int c = count.incrementAndGet();
if (c % 100 == 0) {
System.out.println("count: " + count.get() + ", error: " + error.get());
}
} catch (Exception e) {
error.incrementAndGet();
e.printStackTrace();
System.out.println("count: " + count.get() + ", error: " + error.get());
if ("exit".equals(onerror)) {
System.exit(-1);
} else if ("break".equals(onerror)) {
break;
} else if ("sleep".equals(onerror)) {
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
}
} finally {
if (client != null) {
client.close();
}
}
}
}
})
.start();
}
synchronized (PerformanceServerTest.class) {
while (true) {
try {
PerformanceServerTest.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| 7,383 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
/**
* PerformanceClientTest
* <p>
* mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911
*/
class PerformanceClientTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class);
@Test
@SuppressWarnings("unchecked")
public void testClient() throws Throwable {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
final int length = PerformanceUtils.getIntProperty("length", 1024);
final int connections = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1);
final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100);
int r = PerformanceUtils.getIntProperty("runs", 10000);
final int runs = r > 0 ? r : Integer.MAX_VALUE;
final String onerror = PerformanceUtils.getProperty("onerror", "continue");
final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization
+ "&timeout=" + timeout;
// Create clients and build connections
final ExchangeClient[] exchangeClients = new ExchangeClient[connections];
for (int i = 0; i < connections; i++) {
// exchangeClients[i] = Exchangers.connect(url,handler);
exchangeClients[i] = Exchangers.connect(url);
}
List<String> serverEnvironment =
(List<String>) exchangeClients[0].request("environment").get();
List<String> serverScene =
(List<String>) exchangeClients[0].request("scene").get();
// Create some data for test
StringBuilder buf = new StringBuilder(length);
for (int i = 0; i < length; i++) {
buf.append('A');
}
final String data = buf.toString();
// counters
final AtomicLong count = new AtomicLong();
final AtomicLong error = new AtomicLong();
final AtomicLong time = new AtomicLong();
final AtomicLong all = new AtomicLong();
// Start multiple threads
final CountDownLatch latch = new CountDownLatch(concurrent);
for (int i = 0; i < concurrent; i++) {
new Thread(new Runnable() {
public void run() {
try {
AtomicInteger index = new AtomicInteger();
long init = System.currentTimeMillis();
for (int i = 0; i < runs; i++) {
try {
count.incrementAndGet();
ExchangeClient client = exchangeClients[index.getAndIncrement() % connections];
long start = System.currentTimeMillis();
String result =
(String) client.request(data).get();
long end = System.currentTimeMillis();
if (!data.equals(result)) {
throw new IllegalStateException("Invalid result " + result);
}
time.addAndGet(end - start);
} catch (Exception e) {
error.incrementAndGet();
e.printStackTrace();
if ("exit".equals(onerror)) {
System.exit(-1);
} else if ("break".equals(onerror)) {
break;
} else if ("sleep".equals(onerror)) {
try {
Thread.sleep(30000);
} catch (InterruptedException e1) {
}
}
}
}
all.addAndGet(System.currentTimeMillis() - init);
} finally {
latch.countDown();
}
}
})
.start();
}
// Output, tps is not for accuracy, but it reflects the situation to a certain extent.
new Thread(new Runnable() {
public void run() {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
long lastCount = count.get();
long sleepTime = 2000;
long elapsd = sleepTime / 1000;
boolean bfirst = true;
while (latch.getCount() > 0) {
long c = count.get() - lastCount;
if (!bfirst) // The first time is inaccurate.
System.out.println("[" + dateFormat.format(new Date()) + "] count: " + count.get()
+ ", error: " + error.get() + ",tps:" + (c / elapsd));
bfirst = false;
lastCount = count.get();
Thread.sleep(sleepTime);
}
} catch (Exception e) {
e.printStackTrace();
}
}
})
.start();
latch.await();
for (ExchangeClient client : exchangeClients) {
if (client.isConnected()) {
client.close();
}
}
long total = count.get();
long failed = error.get();
long succeeded = total - failed;
long elapsed = time.get();
long allElapsed = all.get();
long clientElapsed = allElapsed - elapsed;
long art = 0;
long qps = 0;
long throughput = 0;
if (elapsed > 0) {
art = elapsed / succeeded;
qps = concurrent * succeeded * 1000 / elapsed;
throughput = concurrent * succeeded * length * 2 * 1000 / elapsed;
}
PerformanceUtils.printBorder();
PerformanceUtils.printHeader("Dubbo Remoting Performance Test Report");
PerformanceUtils.printBorder();
PerformanceUtils.printHeader("Test Environment");
PerformanceUtils.printSeparator();
for (String item : serverEnvironment) {
PerformanceUtils.printBody("Server " + item);
}
PerformanceUtils.printSeparator();
List<String> clientEnvironment = PerformanceUtils.getEnvironment();
for (String item : clientEnvironment) {
PerformanceUtils.printBody("Client " + item);
}
PerformanceUtils.printSeparator();
PerformanceUtils.printHeader("Test Scene");
PerformanceUtils.printSeparator();
for (String item : serverScene) {
PerformanceUtils.printBody("Server " + item);
}
PerformanceUtils.printBody("Client Transporter: " + transporter);
PerformanceUtils.printBody("Serialization: " + serialization);
PerformanceUtils.printBody("Response Timeout: " + timeout + " ms");
PerformanceUtils.printBody("Data Length: " + length + " bytes");
PerformanceUtils.printBody("Client Shared Connections: " + connections);
PerformanceUtils.printBody("Client Concurrent Threads: " + concurrent);
PerformanceUtils.printBody("Run Times Per Thread: " + runs);
PerformanceUtils.printSeparator();
PerformanceUtils.printHeader("Test Result");
PerformanceUtils.printSeparator();
PerformanceUtils.printBody(
"Succeeded Requests: " + DecimalFormat.getIntegerInstance().format(succeeded));
PerformanceUtils.printBody("Failed Requests: " + failed);
PerformanceUtils.printBody("Client Elapsed Time: " + clientElapsed + " ms");
PerformanceUtils.printBody("Average Response Time: " + art + " ms");
PerformanceUtils.printBody("Requests Per Second: " + qps + "/s");
PerformanceUtils.printBody(
"Throughput Per Second: " + DecimalFormat.getIntegerInstance().format(throughput) + " bytes/s");
PerformanceUtils.printBorder();
}
static class PeformanceTestHandler extends ExchangeHandlerAdapter {
public PeformanceTestHandler() {
super(FrameworkModel.defaultModel());
}
@Override
public void connected(Channel channel) throws RemotingException {
System.out.println("connected event,chanel;" + channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
System.out.println("disconnected event,chanel;" + channel);
}
}
}
| 7,384 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/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.remoting;
import org.apache.dubbo.common.URL;
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;
}
}
| 7,385 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/ChanelHandlerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
/**
* ChanelHandlerTest
* <p>
* mvn clean test -Dtest=*PerformanceClientTest -Dserver=10.20.153.187:9911
*/
class ChanelHandlerTest {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ChanelHandlerTest.class);
public static ExchangeClient initClient(String url) {
// Create client and build connection
ExchangeClient exchangeClient = null;
PeformanceTestHandler handler = new PeformanceTestHandler(url);
boolean run = true;
while (run) {
try {
exchangeClient = Exchangers.connect(url, handler);
} catch (Throwable t) {
if (t != null
&& t.getCause() != null
&& t.getCause().getClass() != null
&& (t.getCause().getClass() == java.net.ConnectException.class
|| t.getCause().getClass() == java.net.ConnectException.class)) {
} else {
t.printStackTrace();
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (exchangeClient != null) {
run = false;
}
}
return exchangeClient;
}
public static void closeClient(ExchangeClient client) {
if (client.isConnected()) {
client.close();
}
}
@Test
void testClient() throws Throwable {
// read server info from property
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60);
final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization
+ "&timeout=" + timeout;
ExchangeClient exchangeClient = initClient(url);
Thread.sleep(sleep);
closeClient(exchangeClient);
}
static class PeformanceTestHandler extends ExchangeHandlerAdapter {
String url = "";
/**
* @param url
*/
public PeformanceTestHandler(String url) {
super(FrameworkModel.defaultModel());
this.url = url;
}
@Override
public void connected(Channel channel) throws RemotingException {
System.out.println("connected event,chanel;" + channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
System.out.println("disconnected event,chanel;" + channel);
initClient(url);
}
/* (non-Javadoc)
* @see org.apache.dubbo.remoting.transport.support.ChannelHandlerAdapter#caught(org.apache.dubbo.remoting.Channel, java.lang.Throwable)
*/
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
// System.out.println("caught event:"+exception);
}
}
}
| 7,386 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientMain.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
/**
* PerformanceClientMain
*/
public class PerformanceClientMain {
public static void main(String[] args) throws Throwable {
new PerformanceClientTest().testClient();
}
}
| 7,387 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TransportersTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.URL;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class TransportersTest {
private String url = "dubbo://127.0.0.1:12345?transporter=mockTransporter";
private ChannelHandler channel = Mockito.mock(ChannelHandler.class);
@Test
void testBind() throws RemotingException {
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind((String) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind((URL) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.bind(url));
Assertions.assertNotNull(Transporters.bind(url, channel));
Assertions.assertNotNull(Transporters.bind(url, channel, channel));
}
@Test
void testConnect() throws RemotingException {
Assertions.assertThrows(RuntimeException.class, () -> Transporters.connect((String) null));
Assertions.assertThrows(RuntimeException.class, () -> Transporters.connect((URL) null));
Assertions.assertNotNull(Transporters.connect(url));
Assertions.assertNotNull(Transporters.connect(url, channel));
Assertions.assertNotNull(Transporters.connect(url, channel, channel));
}
}
| 7,388 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.remoting.transport.dispatcher.execution.ExecutionDispatcher;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADPOOL;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS;
import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
import static org.apache.dubbo.remoting.Constants.BUFFER_KEY;
import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE;
/**
* PerformanceServer
* <p>
* mvn clean test -Dtest=*PerformanceServerTest -Dport=9911
*/
class PerformanceServerTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceServerTest.class);
private static ExchangeServer server = null;
private static void restartServer(int times, int alive, int sleep) throws Exception {
if (server != null && !server.isClosed()) {
server.close();
Thread.sleep(100);
}
for (int i = 0; i < times; i++) {
logger.info("restart times:" + i);
server = statServer();
if (alive > 0) Thread.sleep(alive);
server.close();
if (sleep > 0) Thread.sleep(sleep);
}
server = statServer();
}
private static ExchangeServer statServer() throws Exception {
final int port = PerformanceUtils.getIntProperty("port", 9911);
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final String threadpool = PerformanceUtils.getProperty(THREADPOOL_KEY, DEFAULT_THREADPOOL);
final int threads = PerformanceUtils.getIntProperty(THREADS_KEY, DEFAULT_THREADS);
final int iothreads = PerformanceUtils.getIntProperty(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS);
final int buffer = PerformanceUtils.getIntProperty(BUFFER_KEY, DEFAULT_BUFFER_SIZE);
final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispatcher.NAME);
// Start server
ExchangeServer server = Exchangers.bind(
"exchange://0.0.0.0:" + port + "?transporter="
+ transporter + "&serialization="
+ serialization + "&threadpool=" + threadpool
+ "&threads=" + threads + "&iothreads=" + iothreads + "&buffer=" + buffer + "&channel.handler="
+ channelHandler,
new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) {
public String telnet(Channel channel, String message) throws RemotingException {
return "echo: " + message + "\r\ntelnet> ";
}
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request)
throws RemotingException {
if ("environment".equals(request)) {
return CompletableFuture.completedFuture(PerformanceUtils.getEnvironment());
}
if ("scene".equals(request)) {
List<String> scene = new ArrayList<String>();
scene.add("Transporter: " + transporter);
scene.add("Service Threads: " + threads);
return CompletableFuture.completedFuture(scene);
}
return CompletableFuture.completedFuture(request);
}
});
return server;
}
private static ExchangeServer statTelnetServer(int port) throws Exception {
// Start server
ExchangeServer telnetserver = Exchangers.bind(
"exchange://0.0.0.0:" + port, new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) {
public String telnet(Channel channel, String message) throws RemotingException {
if (message.equals("help")) {
return "support cmd: \r\n\tstart \r\n\tstop \r\n\tshutdown \r\n\trestart times [alive] [sleep] \r\ntelnet>";
} else if (message.equals("stop")) {
logger.info("server closed:" + server);
server.close();
return "stop server\r\ntelnet>";
} else if (message.startsWith("start")) {
try {
restartServer(0, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
return "start server\r\ntelnet>";
} else if (message.startsWith("shutdown")) {
System.exit(0);
return "start server\r\ntelnet>";
} else if (message.startsWith("channels")) {
return "server.getExchangeChannels():"
+ server.getExchangeChannels().size() + "\r\ntelnet>";
} else if (message.startsWith("restart ")) { // r times [sleep] r 10 or r 10 100
String[] args = message.split(" ");
int times = Integer.parseInt(args[1]);
int alive = args.length > 2 ? Integer.parseInt(args[2]) : 0;
int sleep = args.length > 3 ? Integer.parseInt(args[3]) : 100;
try {
restartServer(times, alive, sleep);
} catch (Exception e) {
e.printStackTrace();
}
return "restart server,times:" + times + " stop alive time: " + alive + ",sleep time: "
+ sleep + " usage:r times [alive] [sleep] \r\ntelnet>";
} else {
return "echo: " + message + "\r\ntelnet> ";
}
}
});
return telnetserver;
}
@Test
void testServer() throws Exception {
// Read port from property
if (PerformanceUtils.getProperty("port", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dport=9911");
return;
}
final int port = PerformanceUtils.getIntProperty("port", 9911);
final boolean telnet = PerformanceUtils.getBooleanProperty("telnet", true);
if (telnet) statTelnetServer(port + 1);
server = statServer();
synchronized (PerformanceServerTest.class) {
while (true) {
try {
PerformanceServerTest.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| 7,389 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceUtils.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* PerformanceUtils
*/
public class PerformanceUtils {
private static final int WIDTH = 64;
public static String getProperty(String key, String defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return value.trim();
}
public static int getIntProperty(String key, int defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return Integer.parseInt(value.trim());
}
public static boolean getBooleanProperty(String key, boolean defaultValue) {
String value = System.getProperty(key);
if (value == null || value.trim().length() == 0 || value.startsWith("$")) {
return defaultValue;
}
return Boolean.parseBoolean(value.trim());
}
public static List<String> getEnvironment() {
List<String> environment = new ArrayList<String>();
environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
+ System.getProperty("os.arch", ""));
environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores");
environment.add(
"JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
environment.add("Memory: "
+ DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory()) + " bytes (Max: "
+ DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)");
NetworkInterface ni = PerformanceUtils.getNetworkInterface();
if (ni != null) {
environment.add("Network: " + ni.getDisplayName());
}
return environment;
}
public static void printSeparator() {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < WIDTH; i++) {
pad.append('-');
}
System.out.println("+" + pad + "+");
}
public static void printBorder() {
StringBuilder pad = new StringBuilder();
for (int i = 0; i < WIDTH; i++) {
pad.append('=');
}
System.out.println("+" + pad + "+");
}
public static void printBody(String msg) {
StringBuilder pad = new StringBuilder();
int len = WIDTH - msg.length() - 1;
if (len > 0) {
for (int i = 0; i < len; i++) {
pad.append(' ');
}
}
System.out.println("| " + msg + pad + "|");
}
public static void printHeader(String msg) {
StringBuilder pad = new StringBuilder();
int len = WIDTH - msg.length();
if (len > 0) {
int half = len / 2;
for (int i = 0; i < half; i++) {
pad.append(' ');
}
}
System.out.println("|" + pad + msg + pad + ((len % 2 == 0) ? "" : " ") + "|");
}
public static NetworkInterface getNetworkInterface() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
try {
return interfaces.nextElement();
} catch (Throwable e) {
}
}
}
} catch (SocketException e) {
}
return null;
}
}
| 7,390 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceClientFixedTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.Exchangers;
import java.util.ArrayList;
import java.util.Random;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_ARGUMENT;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
class PerformanceClientFixedTest {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(PerformanceClientTest.class);
@Test
void testClient() throws Exception {
// read the parameters
if (PerformanceUtils.getProperty("server", null) == null) {
logger.warn(CONFIG_UNDEFINED_ARGUMENT, "", "", "Please set -Dserver=127.0.0.1:9911");
return;
}
final String server = System.getProperty("server", "127.0.0.1:9911");
final String transporter =
PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
final String serialization = PerformanceUtils.getProperty(
Constants.SERIALIZATION_KEY, DefaultSerializationSelector.getDefaultRemotingSerialization());
final int timeout = PerformanceUtils.getIntProperty(TIMEOUT_KEY, DEFAULT_TIMEOUT);
// final int length = PerformanceUtils.getIntProperty("length", 1024);
final int connectionCount = PerformanceUtils.getIntProperty(CONNECTIONS_KEY, 1);
// final int concurrent = PerformanceUtils.getIntProperty("concurrent", 100);
// int r = PerformanceUtils.getIntProperty("runs", 10000);
// final int runs = r > 0 ? r : Integer.MAX_VALUE;
// final String onerror = PerformanceUtils.getProperty("onerror", "continue");
final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization
+ "&timeout=" + timeout;
// int idx = server.indexOf(':');
Random rd = new Random(connectionCount);
ArrayList<ExchangeClient> arrays = new ArrayList<ExchangeClient>();
String oneKBlock = null;
String messageBlock = null;
int s = 0;
int f = 0;
System.out.println("initialize arrays " + url);
while (s < connectionCount) {
ExchangeClient client = null;
try {
System.out.println("open connection " + s + " " + url + arrays.size());
client = Exchangers.connect(url);
System.out.println("run after open");
if (client.isConnected()) {
arrays.add(client);
s++;
System.out.println("open client success " + s);
} else {
System.out.println("open client failed, try again.");
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (client != null && !client.isConnected()) {
f++;
System.out.println("open client failed, try again " + f);
client.close();
}
}
}
StringBuilder sb1 = new StringBuilder();
Random rd2 = new Random();
char[] numbersAndLetters =
("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
int size1 = numbersAndLetters.length;
for (int j = 0; j < 1024; j++) {
sb1.append(numbersAndLetters[rd2.nextInt(size1)]);
}
oneKBlock = sb1.toString();
for (int j = 0; j < Integer.MAX_VALUE; j++) {
try {
String size = "10";
int request_size = 10;
try {
request_size = Integer.parseInt(size);
} catch (Throwable t) {
request_size = 10;
}
if (messageBlock == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < request_size; i++) {
sb.append(oneKBlock);
}
messageBlock = sb.toString();
System.out.println("set messageBlock to " + messageBlock);
}
int index = rd.nextInt(connectionCount);
ExchangeClient client = arrays.get(index);
// ExchangeClient client = arrays.get(0);
String output = (String) client.request(messageBlock).get();
if (output.lastIndexOf(messageBlock) < 0) {
System.out.println("send messageBlock;get " + output);
throw new Throwable("return results invalid");
} else {
if (j % 100 == 0) System.out.println("OK: " + j);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
| 7,391 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/PerformanceServerMain.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
/**
* PerformanceServerMain
*/
public class PerformanceServerMain {
public static void main(String[] args) throws Exception {
new PerformanceServerTest().testServer();
}
}
| 7,392 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/TelnetServer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
/**
* TelnetServer
*/
public class TelnetServer {
public static void main(String[] args) throws Exception {
Transporters.bind("telnet://0.0.0.0:23", new ChannelHandlerAdapter() {
@Override
public void connected(Channel channel) throws RemotingException {
channel.send("telnet> ");
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
channel.send("Echo: " + message + "\r\n");
channel.send("telnet> ");
}
});
// Prevent JVM from exiting
synchronized (TelnetServer.class) {
while (true) {
try {
TelnetServer.class.wait();
} catch (InterruptedException e) {
}
}
}
}
}
| 7,393 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/HeaderExchangeHandlerTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.handler;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeHandler;
import org.apache.dubbo.remoting.exchange.Request;
import org.apache.dubbo.remoting.exchange.Response;
import org.apache.dubbo.remoting.exchange.support.DefaultFuture;
import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT;
import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT;
// TODO response test
class HeaderExchangeHandlerTest {
@Test
void testReceivedRequestOneway() throws RemotingException {
final Channel mockChannel = new MockedChannel();
final Person requestData = new Person("charles");
Request request = new Request();
request.setTwoWay(false);
request.setData(requestData);
ExchangeHandler exHandler = new MockedExchangeHandler() {
@Override
public void received(Channel channel, Object message) throws RemotingException {
Assertions.assertEquals(requestData, message);
}
};
HeaderExchangeHandler headExHandler = new HeaderExchangeHandler(exHandler);
headExHandler.received(mockChannel, request);
}
@Test
void testReceivedRequestTwoway() throws RemotingException {
final Person requestData = new Person("charles");
final Request request = new Request();
request.setTwoWay(true);
request.setData(requestData);
final AtomicInteger count = new AtomicInteger(0);
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Response res = (Response) message;
Assertions.assertEquals(request.getId(), res.getId());
Assertions.assertEquals(request.getVersion(), res.getVersion());
Assertions.assertEquals(Response.OK, res.getStatus());
Assertions.assertEquals(requestData, res.getResult());
Assertions.assertNull(res.getErrorMessage());
count.incrementAndGet();
}
};
ExchangeHandler exHandler = new MockedExchangeHandler() {
@Override
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
return CompletableFuture.completedFuture(request);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
Assertions.fail();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(exHandler);
headerExchangeHandler.received(mockChannel, request);
Assertions.assertEquals(1, count.get());
}
@Test
void testReceivedRequestTwowayErrorWithNullHandler() throws RemotingException {
Assertions.assertThrows(IllegalArgumentException.class, () -> new HeaderExchangeHandler(null));
}
@Test
void testReceivedRequestTwowayErrorReply() throws RemotingException {
final Person requestData = new Person("charles");
final Request request = new Request();
request.setTwoWay(true);
request.setData(requestData);
final AtomicInteger count = new AtomicInteger(0);
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Response res = (Response) message;
Assertions.assertEquals(request.getId(), res.getId());
Assertions.assertEquals(request.getVersion(), res.getVersion());
Assertions.assertEquals(Response.SERVICE_ERROR, res.getStatus());
Assertions.assertNull(res.getResult());
Assertions.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
count.incrementAndGet();
}
};
ExchangeHandler exHandler = new MockedExchangeHandler() {
@Override
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
throw new BizException();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(exHandler);
headerExchangeHandler.received(mockChannel, request);
Assertions.assertEquals(1, count.get());
}
@Test
void testReceivedRequestTwowayErrorRequestBroken() throws RemotingException {
final Request request = new Request();
request.setTwoWay(true);
request.setData(new BizException());
request.setBroken(true);
final AtomicInteger count = new AtomicInteger(0);
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Response res = (Response) message;
Assertions.assertEquals(request.getId(), res.getId());
Assertions.assertEquals(request.getVersion(), res.getVersion());
Assertions.assertEquals(Response.BAD_REQUEST, res.getStatus());
Assertions.assertNull(res.getResult());
Assertions.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
count.incrementAndGet();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
headerExchangeHandler.received(mockChannel, request);
Assertions.assertEquals(1, count.get());
}
@Test
void testReceivedRequestEventReadonly() throws RemotingException {
final Request request = new Request();
request.setTwoWay(true);
request.setEvent(READONLY_EVENT);
final Channel mockChannel = new MockedChannel();
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
headerExchangeHandler.received(mockChannel, request);
Assertions.assertTrue(mockChannel.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY));
}
@Test
void testReceivedRequestEventOtherDiscard() throws RemotingException {
final Request request = new Request();
request.setTwoWay(true);
request.setEvent("my event");
final Channel mockChannel = new MockedChannel() {
@Override
public void send(Object message) throws RemotingException {
Assertions.fail();
}
};
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler() {
@Override
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
Assertions.fail();
throw new RemotingException(channel, "");
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
Assertions.fail();
throw new RemotingException(channel, "");
}
});
headerExchangeHandler.received(mockChannel, request);
}
@Test
void testReceivedResponseHeartbeatEvent() throws Exception {
Channel mockChannel = new MockedChannel();
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
Response response = new Response(1);
response.setStatus(Response.OK);
response.setEvent(true);
response.setResult(HEARTBEAT_EVENT);
headerExchangeHandler.received(mockChannel, response);
}
@Test
void testReceivedResponse() throws Exception {
Request request = new Request(1);
request.setTwoWay(true);
Channel mockChannel = new MockedChannel();
DefaultFuture future = DefaultFuture.newFuture(mockChannel, request, 5000, null);
HeaderExchangeHandler headerExchangeHandler = new HeaderExchangeHandler(new MockedExchangeHandler());
Response response = new Response(1);
response.setStatus(Response.OK);
response.setResult("MOCK_DATA");
headerExchangeHandler.received(mockChannel, response);
Object result = future.get();
Assertions.assertEquals(result.toString(), "MOCK_DATA");
}
private class BizException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
private class MockedExchangeHandler extends MockedChannelHandler implements ExchangeHandler {
public String telnet(Channel channel, String message) throws RemotingException {
throw new UnsupportedOperationException();
}
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
throw new UnsupportedOperationException();
}
}
private class Person {
private String name;
public Person(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
}
}
| 7,394 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannelHandler.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.handler;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.util.Collections;
import java.util.Set;
public class MockedChannelHandler implements ChannelHandler {
// ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();
ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>();
@Override
public void connected(Channel channel) throws RemotingException {
channels.add(channel);
}
@Override
public void disconnected(Channel channel) throws RemotingException {
channels.remove(channel);
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {
channel.send(message);
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
// echo
channel.send(message);
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
throw new RemotingException(channel, exception);
}
public Set<Channel> getChannels() {
return Collections.unmodifiableSet(channels);
}
}
| 7,395 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/handler/MockedChannel.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.handler;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
public class MockedChannel implements Channel {
private boolean isClosed;
private volatile boolean closing = false;
private URL url;
private ChannelHandler handler;
private Map<String, Object> map = new HashMap<String, Object>();
public MockedChannel() {
super();
}
@Override
public URL getUrl() {
return url;
}
@Override
public ChannelHandler getChannelHandler() {
return this.handler;
}
@Override
public InetSocketAddress getLocalAddress() {
return null;
}
@Override
public void send(Object message) throws RemotingException {}
@Override
public void send(Object message, boolean sent) throws RemotingException {
this.send(message);
}
@Override
public void close() {
isClosed = true;
}
@Override
public void close(int timeout) {
this.close();
}
@Override
public void startClose() {
closing = true;
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public InetSocketAddress getRemoteAddress() {
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean hasAttribute(String key) {
return map.containsKey(key);
}
@Override
public Object getAttribute(String key) {
return map.get(key);
}
@Override
public void setAttribute(String key, Object value) {
map.put(key, value);
}
@Override
public void removeAttribute(String key) {
map.remove(key);
}
}
| 7,396 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/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.remoting.exchange;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingException;
import org.mockito.Mockito;
public class MockExchanger implements Exchanger {
private ExchangeServer exchangeServer = Mockito.mock(ExchangeServer.class);
private ExchangeClient exchangeClient = Mockito.mock(ExchangeClient.class);
@Override
public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException {
return exchangeServer;
}
@Override
public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException {
return exchangeClient;
}
}
| 7,397 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/ExchangersTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerDispatcher;
import org.apache.dubbo.remoting.exchange.support.Replier;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ExchangersTest {
@Test
void testBind() throws RemotingException {
String url = "dubbo://127.0.0.1:12345?exchanger=mockExchanger";
Exchangers.bind(url, Mockito.mock(Replier.class));
Exchangers.bind(url, new ChannelHandlerAdapter(), Mockito.mock(Replier.class));
Exchangers.bind(url, new ExchangeHandlerDispatcher());
Assertions.assertThrows(
RuntimeException.class, () -> Exchangers.bind((URL) null, new ExchangeHandlerDispatcher()));
Assertions.assertThrows(RuntimeException.class, () -> Exchangers.bind(url, (ExchangeHandlerDispatcher) null));
}
@Test
void testConnect() throws RemotingException {
String url = "dubbo://127.0.0.1:12345?exchanger=mockExchanger";
Exchangers.connect(url);
Exchangers.connect(url, Mockito.mock(Replier.class));
Exchangers.connect(URL.valueOf(url), Mockito.mock(Replier.class));
Exchangers.connect(url, new ChannelHandlerAdapter(), Mockito.mock(Replier.class));
Exchangers.connect(url, new ExchangeHandlerDispatcher());
Assertions.assertThrows(
RuntimeException.class, () -> Exchangers.connect((URL) null, new ExchangeHandlerDispatcher()));
Assertions.assertThrows(
RuntimeException.class, () -> Exchangers.connect(url, (ExchangeHandlerDispatcher) null));
}
}
| 7,398 |
0 |
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting
|
Create_ds/dubbo/dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/exchange/RequestTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class RequestTest {
@Test
void test() {
Request requestStart = new Request();
Request request = new Request();
request.setTwoWay(true);
request.setBroken(true);
request.setVersion("1.0.0");
request.setEvent(true);
request.setData("data");
request.setPayload(1024);
Assertions.assertTrue(request.isTwoWay());
Assertions.assertTrue(request.isBroken());
Assertions.assertTrue(request.isEvent());
Assertions.assertEquals(request.getVersion(), "1.0.0");
Assertions.assertEquals(request.getData(), "data");
Assertions.assertEquals(requestStart.getId() + 1, request.getId());
Assertions.assertEquals(1024, request.getPayload());
request.setHeartbeat(true);
Assertions.assertTrue(request.isHeartbeat());
Request copiedRequest = request.copy();
Assertions.assertEquals(copiedRequest.toString(), request.toString());
Request copyWithoutData = request.copyWithoutData();
Assertions.assertNull(copyWithoutData.getData());
}
}
| 7,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.