repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import java.util.Map;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getNonStaticFields;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getType;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isClassType;
/**
* {@link TypeBuilder} for General Object
*
* @since 2.7.6
*/
public class GeneralTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder {
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
return isClassType(type);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
String typeName = type.toString();
TypeElement typeElement = getType(processingEnv, typeName);
return buildProperties(processingEnv, typeElement, typeCache);
}
protected TypeDefinition buildProperties(
ProcessingEnvironment processingEnv, TypeElement type, Map<String, TypeDefinition> typeCache) {
TypeDefinition definition = new TypeDefinition(type.toString());
getNonStaticFields(type).forEach(field -> {
String fieldName = field.getSimpleName().toString();
TypeDefinition propertyType = TypeDefinitionBuilder.build(processingEnv, field, typeCache);
if (propertyType != null) {
typeCache.put(propertyType.getType(), propertyType);
definition.getProperties().put(fieldName, propertyType.getType());
}
});
return definition;
}
@Override
public int getPriority() {
return MIN_PRIORITY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/PrimitiveTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeMirror;
import java.util.Map;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isPrimitiveType;
/**
* {@link TypeBuilder} for Java {@link PrimitiveType primitive type}
*
* @since 2.7.6
*/
public class PrimitiveTypeDefinitionBuilder implements TypeBuilder<PrimitiveType> {
@Override
public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) {
return isPrimitiveType(type);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, PrimitiveType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = new TypeDefinition(type.toString());
return typeDefinition;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 3;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/DeclaredTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/DeclaredTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.ofDeclaredType;
/**
* An interface of {@link TypeBuilder} for {@link DeclaredType}
*
* @since 2.7.6
*/
public interface DeclaredTypeDefinitionBuilder extends TypeBuilder<DeclaredType> {
@Override
default boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) {
DeclaredType declaredType = ofDeclaredType(type);
if (declaredType == null) {
return false;
}
return accept(processingEnv, declaredType);
}
/**
* Test the specified {@link DeclaredType type} is accepted or not
*
* @param processingEnv {@link ProcessingEnvironment}
* @param type {@link DeclaredType type}
* @return <code>true</code> if accepted
*/
boolean accept(ProcessingEnvironment processingEnv, DeclaredType type);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import org.apache.dubbo.rpc.model.ApplicationModel;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.type.TypeMirror;
import java.util.Map;
/**
* A class builds the instance of {@link TypeDefinition}
*
* @since 2.7.6
*/
public interface TypeDefinitionBuilder<T extends TypeMirror> extends Prioritized {
/**
* Build the instance of {@link TypeDefinition} from the specified {@link Element element}
*
* @param processingEnv {@link ProcessingEnvironment}
* @param element {@link Element source element}
* @return non-null
*/
static TypeDefinition build(
ProcessingEnvironment processingEnv, Element element, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = build(processingEnv, element.asType(), typeCache);
// Comment this code for the compatibility
// typeDefinition.set$ref(element.toString());
return typeDefinition;
}
/**
* Build the instance of {@link TypeDefinition} from the specified {@link TypeMirror type}
*
* @param processingEnv {@link ProcessingEnvironment}
* @param type {@link TypeMirror type}
* @return non-null
*/
static TypeDefinition build(
ProcessingEnvironment processingEnv, TypeMirror type, Map<String, TypeDefinition> typeCache) {
// Build by all instances of TypeDefinitionBuilder that were loaded By Java SPI
TypeDefinition typeDefinition =
ApplicationModel.defaultModel()
.getExtensionLoader(TypeBuilder.class)
.getSupportedExtensionInstances()
.stream()
// load(TypeDefinitionBuilder.class, TypeDefinitionBuilder.class.getClassLoader())
.filter(builder -> builder.accept(processingEnv, type))
.findFirst()
.map(builder -> {
return builder.build(processingEnv, type, typeCache);
// typeDefinition.setTypeBuilderName(builder.getClass().getName());
})
.orElse(null);
if (typeDefinition != null) {
typeCache.put(typeDefinition.getType(), typeDefinition);
}
return typeDefinition;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ServiceDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getPublicNonStaticMethods;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getHierarchicalTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.getResourceName;
/**
* A Builder for {@link ServiceDefinition}
*
* @see ServiceDefinition
* @since 2.7.6
*/
public interface ServiceDefinitionBuilder {
static ServiceDefinition build(ProcessingEnvironment processingEnv, TypeElement type) {
ServiceDefinition serviceDefinition = new ServiceDefinition();
serviceDefinition.setCanonicalName(type.toString());
serviceDefinition.setCodeSource(getResourceName(type.toString()));
Map<String, TypeDefinition> types = new HashMap<>();
// Get all super types and interface excluding the specified type
// and then the result will be added into ServiceDefinition#getTypes()
getHierarchicalTypes(type.asType(), Object.class)
.forEach(t -> TypeDefinitionBuilder.build(processingEnv, t, types));
// Get all declared methods that will be added into ServiceDefinition#getMethods()
getPublicNonStaticMethods(type, Object.class).stream()
.map(method -> MethodDefinitionBuilder.build(processingEnv, method, types))
.forEach(serviceDefinition.getMethods()::add);
serviceDefinition.setTypes(new ArrayList<>(types.values()));
return serviceDefinition;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/TypeBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.TypeMirror;
import java.util.Map;
@SPI
public interface TypeBuilder<T extends TypeMirror> extends Prioritized {
/**
* Test the specified {@link TypeMirror type} is accepted or not
*
* @param processingEnv {@link ProcessingEnvironment}
* @param type {@link TypeMirror type}
* @return <code>true</code> if accepted
*/
boolean accept(ProcessingEnvironment processingEnv, TypeMirror type);
/**
* Build the instance of {@link TypeDefinition}
*
* @param processingEnv {@link ProcessingEnvironment}
* @param type {@link T type}
* @return an instance of {@link TypeDefinition}
*/
TypeDefinition build(ProcessingEnvironment processingEnv, T type, Map<String, TypeDefinition> typeCache);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MapTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import java.util.Map;
import java.util.Objects;
/**
* {@link TypeBuilder} for Java {@link Map}
*
* @since 2.7.6
*/
public class MapTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder {
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
Elements elements = processingEnv.getElementUtils();
TypeElement mapTypeElement = elements.getTypeElement(Map.class.getTypeName());
TypeMirror mapType = mapTypeElement.asType();
Types types = processingEnv.getTypeUtils();
TypeMirror erasedType = types.erasure(type);
return types.isAssignable(erasedType, mapType);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = new TypeDefinition(type.toString());
// Generic Type arguments
type.getTypeArguments().stream()
.map(typeArgument -> TypeDefinitionBuilder.build(
processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument
.filter(Objects::nonNull)
.map(TypeDefinition::getType)
.forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition
return typeDefinition;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 6;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/MethodDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.MethodDefinition;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.ExecutableElement;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodName;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getMethodParameterTypes;
import static org.apache.dubbo.metadata.annotation.processing.util.MethodUtils.getReturnType;
/**
* A Builder class for {@link MethodDefinition}
*
* @see MethodDefinition
* @since 2.7.6
*/
public interface MethodDefinitionBuilder {
static MethodDefinition build(
ProcessingEnvironment processingEnv, ExecutableElement method, Map<String, TypeDefinition> typeCache) {
MethodDefinition methodDefinition = new MethodDefinition();
methodDefinition.setName(getMethodName(method));
methodDefinition.setReturnType(getReturnType(method));
methodDefinition.setParameterTypes(getMethodParameterTypes(method));
methodDefinition.setParameters(getMethodParameters(processingEnv, method, typeCache));
return methodDefinition;
}
static List<TypeDefinition> getMethodParameters(
ProcessingEnvironment processingEnv, ExecutableElement method, Map<String, TypeDefinition> typeCache) {
return method.getParameters().stream()
.map(element -> TypeDefinitionBuilder.build(processingEnv, element, typeCache))
.collect(Collectors.toList());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/EnumTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.annotation.processing.util.FieldUtils;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.type.DeclaredType;
import java.util.Map;
import static org.apache.dubbo.metadata.annotation.processing.util.FieldUtils.getDeclaredFields;
import static org.apache.dubbo.metadata.annotation.processing.util.TypeUtils.isEnumType;
/**
* {@link TypeBuilder} for Java {@link Enum}
*
* @since 2.7.6
*/
public class EnumTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder {
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
return isEnumType(type);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = new TypeDefinition(type.toString());
getDeclaredFields(type, FieldUtils::isEnumMemberField).stream()
.map(Element::getSimpleName)
.map(Name::toString)
.forEach(typeDefinition.getEnums()::add);
return typeDefinition;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 2;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/CollectionTypeDefinitionBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.processing.builder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
/**
* {@link TypeBuilder} for Java {@link Collection}
*
* @since 2.7.6
*/
public class CollectionTypeDefinitionBuilder implements DeclaredTypeDefinitionBuilder {
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
Elements elements = processingEnv.getElementUtils();
TypeElement collectionTypeElement = elements.getTypeElement(Collection.class.getTypeName());
TypeMirror collectionType = collectionTypeElement.asType();
Types types = processingEnv.getTypeUtils();
TypeMirror erasedType = types.erasure(type);
return types.isAssignable(erasedType, collectionType);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, DeclaredType type, Map<String, TypeDefinition> typeCache) {
String typeName = type.toString();
TypeDefinition typeDefinition = new TypeDefinition(typeName);
// Generic Type arguments
type.getTypeArguments().stream()
.map(typeArgument -> TypeDefinitionBuilder.build(
processingEnv, typeArgument, typeCache)) // build the TypeDefinition from typeArgument
.filter(Objects::nonNull)
.map(TypeDefinition::getType)
.forEach(typeDefinition.getItems()::add); // Add into the declared TypeDefinition
return typeDefinition;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 5;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/AbstractServiceNameMappingTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
import static org.mockito.Mockito.*;
/**
* @see AbstractServiceNameMapping
*/
class AbstractServiceNameMappingTest {
private ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class);
private MockServiceNameMapping mapping;
private MockServiceNameMapping2 mapping2;
URL url = URL.valueOf("dubbo://127.0.0.1:21880/" + AbstractServiceNameMappingTest.class.getName());
@BeforeEach
public void setUp() throws Exception {
org.apache.dubbo.rpc.model.FrameworkModel frameworkModel =
org.apache.dubbo.rpc.model.FrameworkModel.defaultModel();
frameworkModel
.getBeanFactory()
.getOrRegisterBean(org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository.class);
org.apache.dubbo.config.context.ConfigManager configManager =
Mockito.mock(org.apache.dubbo.config.context.ConfigManager.class);
org.apache.dubbo.config.ApplicationConfig appConfig =
Mockito.mock(org.apache.dubbo.config.ApplicationConfig.class);
Mockito.when(applicationModel.getFrameworkModel()).thenReturn(frameworkModel);
Mockito.when(applicationModel.getApplicationConfigManager()).thenReturn(configManager);
Mockito.when(configManager.getApplication()).thenReturn(java.util.Optional.of(appConfig));
Mockito.when(appConfig.getEnableFileCache()).thenReturn(Boolean.TRUE);
Mockito.when(applicationModel.tryGetApplicationName()).thenReturn("unit-test");
mapping = new MockServiceNameMapping(applicationModel);
mapping2 = new MockServiceNameMapping2(applicationModel);
}
@AfterEach
public void clearup() {
mapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url));
}
@Test
void testGetServices() {
url = url.addParameter(PROVIDED_BY, "app1,app2");
Set<String> services = mapping.getMapping(url);
Assertions.assertTrue(services.contains("app1"));
Assertions.assertTrue(services.contains("app2"));
// // remove mapping cache, check get() works.
// mapping.removeCachedMapping(ServiceNameMapping.buildMappingKey(url));
// services = mapping.initInterfaceAppMapping(url);
// Assertions.assertTrue(services.contains("remote-app1"));
// Assertions.assertTrue(services.contains("remote-app2"));
// Assertions.assertNotNull(mapping.getCachedMapping(url));
// Assertions.assertIterableEquals(mapping.getCachedMapping(url), services);
}
@Test
void testGetAndListener() {
URL registryURL = URL.valueOf("registry://127.0.0.1:7777/test");
registryURL = registryURL.addParameter(SUBSCRIBED_SERVICE_NAMES_KEY, "registry-app1");
Set<String> services = mapping2.getAndListen(registryURL, url, null);
Assertions.assertTrue(services.contains("registry-app1"));
// remove mapping cache, check get() works.
mapping2.removeCachedMapping(ServiceNameMapping.buildMappingKey(url));
mapping2.enabled = true;
services = mapping2.getAndListen(registryURL, url, new MappingListener() {
@Override
public void onEvent(MappingChangedEvent event) {}
@Override
public void stop() {}
});
Assertions.assertTrue(services.contains("remote-app3"));
}
private class MockServiceNameMapping extends AbstractServiceNameMapping {
public boolean enabled = false;
public MockServiceNameMapping(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
public Set<String> get(URL url) {
return new HashSet<>(Arrays.asList("remote-app1", "remote-app2"));
}
@Override
public Set<String> getAndListen(URL url, MappingListener mappingListener) {
if (!enabled) {
return Collections.emptySet();
}
return new HashSet<>(Arrays.asList("remote-app3"));
}
@Override
protected void removeListener(URL url, MappingListener mappingListener) {}
@Override
public boolean map(URL url) {
return false;
}
@Override
public boolean hasValidMetadataCenter() {
return false;
}
}
private class MockServiceNameMapping2 extends AbstractServiceNameMapping {
public boolean enabled = false;
public MockServiceNameMapping2(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
public Set<String> get(URL url) {
return Collections.emptySet();
}
@Override
public Set<String> getAndListen(URL url, MappingListener mappingListener) {
if (!enabled) {
return Collections.emptySet();
}
return new HashSet<>(Arrays.asList("remote-app3"));
}
@Override
protected void removeListener(URL url, MappingListener mappingListener) {}
@Override
public boolean map(URL url) {
return false;
}
@Override
public boolean hasValidMetadataCenter() {
return false;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/MetadataInfoTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Some construction and filter cases are covered in InMemoryMetadataServiceTest
*/
class MetadataInfoTest {
private static final Logger logger = LoggerFactory.getLogger(MetadataInfoTest.class);
private static URL url = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService2?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService2"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded");
private static URL url2 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&metadata-type=remote&methods=sayHello&pid=36621&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=customized,-excluded");
private static URL url3 = URL.valueOf("dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-customized,excluded");
private static URL url4 = URL.valueOf(
"dubbo://30.225.21.30:20880/org.apache.dubbo.registry.service.DemoService?"
+ "REGISTRY_CLUSTER=registry1&anyhost=true&application=demo-provider2&delay=5000&deprecated=false&dubbo=2.0.2"
+ "&dynamic=true&generic=false&group=greeting&interface=org.apache.dubbo.registry.service.DemoService"
+ "&metadata-type=remote&methods=sayHello&sayHello.timeout=7000&pid=36621&release=&revision=1.0.0&service-name-mapping=true"
+ "&side=provider&timeout=5000×tamp=1629970068002&version=1.0.0¶ms-filter=-customized,excluded&payload=1024");
@Test
void testEmptyRevision() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
metadataInfo.setApp("demo");
Assertions.assertEquals(EMPTY_REVISION, metadataInfo.calAndGetRevision());
}
@Test
void testParamsFilterIncluded() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
// export normal url again
metadataInfo.addService(url);
MetadataInfo.ServiceInfo serviceInfo2 = metadataInfo.getServiceInfo(url.getProtocolServiceKey());
assertNotNull(serviceInfo2);
assertEquals(5, serviceInfo2.getParams().size());
assertNull(serviceInfo2.getParams().get(INTERFACE_KEY));
assertNull(serviceInfo2.getParams().get("delay"));
assertNotNull(serviceInfo2.getParams().get(APPLICATION_KEY));
assertNotNull(serviceInfo2.getParams().get(VERSION_KEY));
assertNotNull(serviceInfo2.getParams().get(GROUP_KEY));
assertNotNull(serviceInfo2.getParams().get(TIMEOUT_KEY));
assertEquals("7000", serviceInfo2.getMethodParameter("sayHello", TIMEOUT_KEY, "1000"));
}
@Test
void testParamsFilterExcluded() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
// export normal url again
metadataInfo.addService(url3);
MetadataInfo.ServiceInfo serviceInfo3 = metadataInfo.getServiceInfo(url3.getProtocolServiceKey());
assertNotNull(serviceInfo3);
assertEquals(14, serviceInfo3.getParams().size());
assertNotNull(serviceInfo3.getParams().get(INTERFACE_KEY));
assertNotNull(serviceInfo3.getParams().get(APPLICATION_KEY));
assertNotNull(serviceInfo3.getParams().get(VERSION_KEY));
assertNull(serviceInfo3.getParams().get(GROUP_KEY));
assertNull(serviceInfo3.getParams().get(TIMEOUT_KEY));
assertNull(serviceInfo3.getParams().get("anyhost"));
assertEquals("1000", serviceInfo3.getMethodParameter("sayHello", TIMEOUT_KEY, "1000"));
}
@Test
void testEqualsAndRevision() {
// same metadata
MetadataInfo metadataInfo = new MetadataInfo("demo");
metadataInfo.addService(url);
MetadataInfo sameMetadataInfo = new MetadataInfo("demo");
sameMetadataInfo.addService(url);
assertEquals(metadataInfo, sameMetadataInfo);
assertEquals(metadataInfo.calAndGetRevision(), sameMetadataInfo.calAndGetRevision());
// url with different params that are not counted in ServiceInfo
MetadataInfo metadataInfoWithDifferentParam1 = new MetadataInfo("demo");
metadataInfoWithDifferentParam1.addService(url.addParameter("delay", 6000));
assertEquals(metadataInfo, metadataInfoWithDifferentParam1);
assertEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentParam1.calAndGetRevision());
// url with different params that are counted in ServiceInfo
MetadataInfo metadataInfoWithDifferentParam2 = new MetadataInfo("demo");
metadataInfoWithDifferentParam2.addService(url.addParameter(TIMEOUT_KEY, 6000));
assertNotEquals(metadataInfo, metadataInfoWithDifferentParam2);
assertNotEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentParam2.calAndGetRevision());
MetadataInfo metadataInfoWithDifferentGroup = new MetadataInfo("demo");
metadataInfoWithDifferentGroup.addService(url.addParameter(GROUP_KEY, "newGroup"));
assertNotEquals(metadataInfo, metadataInfoWithDifferentGroup);
assertNotEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentGroup.calAndGetRevision());
MetadataInfo metadataInfoWithDifferentServices = new MetadataInfo("demo");
metadataInfoWithDifferentServices.addService(url);
metadataInfoWithDifferentServices.addService(url2);
assertNotEquals(metadataInfo, metadataInfoWithDifferentServices);
assertNotEquals(metadataInfo.calAndGetRevision(), metadataInfoWithDifferentServices.calAndGetRevision());
}
@Test
void testChanged() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
metadataInfo.addService(url);
metadataInfo.addService(url2);
assertTrue(metadataInfo.updated);
metadataInfo.calAndGetRevision();
assertFalse(metadataInfo.updated);
metadataInfo.removeService(url2);
assertTrue(metadataInfo.updated);
}
@Test
void testJsonFormat() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
// export normal url again
metadataInfo.addService(url);
logger.info(JsonUtils.toJson(metadataInfo));
MetadataInfo metadataInfo2 = new MetadataInfo("demo");
// export normal url again
metadataInfo2.addService(url);
metadataInfo2.addService(url2);
logger.info(JsonUtils.toJson(metadataInfo2));
}
@Test
void testJdkSerialize() throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
MetadataInfo metadataInfo = new MetadataInfo("demo");
metadataInfo.addService(url);
objectOutputStream.writeObject(metadataInfo);
objectOutputStream.close();
byteArrayOutputStream.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
MetadataInfo metadataInfo2 = (MetadataInfo) objectInputStream.readObject();
objectInputStream.close();
Assertions.assertEquals(metadataInfo, metadataInfo2);
Field initiatedField = MetadataInfo.class.getDeclaredField("initiated");
initiatedField.setAccessible(true);
Assertions.assertInstanceOf(AtomicBoolean.class, initiatedField.get(metadataInfo2));
Assertions.assertFalse(((AtomicBoolean) initiatedField.get(metadataInfo2)).get());
}
@Test
void testCal() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
// export normal url again
metadataInfo.addService(url);
metadataInfo.calAndGetRevision();
metadataInfo.addService(url2);
metadataInfo.calAndGetRevision();
metadataInfo.addService(url3);
metadataInfo.calAndGetRevision();
Map<String, Object> ret = JsonUtils.toJavaObject(metadataInfo.getContent(), Map.class);
assertNull(ret.get("content"));
assertNull(ret.get("rawMetadataInfo"));
}
@Test
void testPayload() {
MetadataInfo metadataInfo = new MetadataInfo("demo");
metadataInfo.addService(url4);
MetadataInfo.ServiceInfo serviceInfo4 = metadataInfo.getServiceInfo(url4.getProtocolServiceKey());
assertNotNull(serviceInfo4);
assertEquals("1024", serviceInfo4.getParameter(PAYLOAD));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
@Activate(order = 1) // Will take effect before ExcludedParamsFilter
public class ExcludedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[] {TIMEOUT_KEY, GROUP_KEY, "anyhost"};
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[0];
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/CustomizedParamsFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
@Activate(order = 3) // Will take effect after ExcludedParamsFilter
public class CustomizedParamsFilter implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[] {APPLICATION_KEY, TIMEOUT_KEY, GROUP_KEY, VERSION_KEY};
}
@Override
public String[] serviceParamsExcluded() {
return new String[0];
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[0];
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/filter/ExcludedParamsFilter2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.filter;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metadata.MetadataParamsFilter;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
@Activate(order = 2) // Will take effect before ExcludedParamsFilter
public class ExcludedParamsFilter2 implements MetadataParamsFilter {
@Override
public String[] serviceParamsIncluded() {
return new String[0];
}
@Override
public String[] serviceParamsExcluded() {
return new String[] {DEPRECATED_KEY, SIDE_KEY};
}
/**
* Not included in this test
*/
@Override
public String[] instanceParamsIncluded() {
return new String[0];
}
@Override
public String[] instanceParamsExcluded() {
return new String[0];
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService2.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* 2018/9/19
*/
public interface InterfaceNameTestService2 {
void test2();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/InterfaceNameTestService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* 2018/9/19
*/
public interface InterfaceNameTestService {
void test();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RetryTestService.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/store/RetryTestService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* 2018/10/26
*/
public interface RetryTestService {
void sayHello(String input);
String getName();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReport4Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.test;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* ZookeeperRegistry
*/
class JTestMetadataReport4Test extends AbstractMetadataReport {
private static final Logger logger = LoggerFactory.getLogger(JTestMetadataReport4Test.class);
public JTestMetadataReport4Test(URL url) {
super(url);
}
public volatile Map<String, String> store = new ConcurrentHashMap<>();
private static String getProtocol(URL url) {
String protocol = url.getSide();
protocol = protocol == null ? url.getProtocol() : protocol;
return protocol;
}
@Override
protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) {
store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString);
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
store.put(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), url.toFullString());
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) {
store.remove(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
return Arrays.asList(store.getOrDefault(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), ""));
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {
store.put(subscriberMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), urls);
}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException("This extension does not support working as a remote metadata center.");
}
public static String getProviderKey(URL url) {
return new MetadataIdentifier(url).getUniqueKey(KeyTypeEnum.UNIQUE_KEY);
}
public static String getConsumerKey(URL url) {
return new MetadataIdentifier(url).getUniqueKey(KeyTypeEnum.UNIQUE_KEY);
}
@Override
public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) {
return store.get(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/test/JTestMetadataReportFactory4Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.test;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
/**
* ZookeeperRegistryFactory.
*/
public class JTestMetadataReportFactory4Test extends AbstractMetadataReportFactory {
@Override
public MetadataReport createMetadataReport(URL url) {
return new JTestMetadataReport4Test(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/MetadataReportInstanceTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class MetadataReportInstanceTest {
private MetadataReportInstance metadataReportInstance;
private MetadataReportConfig metadataReportConfig;
private ConfigManager configManager;
private final String registryId = "9103";
@BeforeEach
public void setUp() {
configManager = mock(ConfigManager.class);
ApplicationModel applicationModel = spy(ApplicationModel.defaultModel());
metadataReportInstance = new MetadataReportInstance(applicationModel);
URL url = URL.valueOf("metadata://127.0.0.1:20880/TestService?version=1.0.0&metadata=JTest");
metadataReportConfig = mock(MetadataReportConfig.class);
when(metadataReportConfig.getUsername()).thenReturn("username");
when(metadataReportConfig.getPassword()).thenReturn("password");
when(metadataReportConfig.getApplicationModel()).thenReturn(applicationModel);
when(metadataReportConfig.toUrl()).thenReturn(url);
when(metadataReportConfig.getScopeModel()).thenReturn(applicationModel);
when(metadataReportConfig.getRegistry()).thenReturn(registryId);
when(configManager.getMetadataConfigs()).thenReturn(Collections.emptyList());
when(applicationModel.getApplicationConfigManager()).thenReturn(configManager);
when(applicationModel.getApplicationConfigManager().getApplicationOrElseThrow())
.thenReturn(new ApplicationConfig("test"));
when(applicationModel.getCurrentConfig()).thenReturn(new ApplicationConfig("test"));
}
@Test
void test() {
Assertions.assertNull(
metadataReportInstance.getMetadataReport(registryId), "the metadata report was not initialized.");
Assertions.assertTrue(metadataReportInstance.getMetadataReports(true).isEmpty());
metadataReportInstance.init(Collections.singletonList(metadataReportConfig));
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryId);
Assertions.assertNotNull(metadataReport);
MetadataReport metadataReport2 = metadataReportInstance.getMetadataReport(registryId + "NOT_EXIST");
Assertions.assertEquals(metadataReport, metadataReport2);
Map<String, MetadataReport> metadataReports = metadataReportInstance.getMetadataReports(true);
Assertions.assertEquals(metadataReports.size(), 1);
Assertions.assertEquals(metadataReports.get(registryId), metadataReport);
Assertions.assertEquals(metadataReportConfig.getUsername(), "username");
Assertions.assertEquals(metadataReportConfig.getPassword(), "password");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* 2018/9/14
*/
class AbstractMetadataReportFactoryTest {
private AbstractMetadataReportFactory metadataReportFactory = new AbstractMetadataReportFactory() {
@Override
protected MetadataReport createMetadataReport(URL url) {
return new MetadataReport() {
@Override
public void storeProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
store.put(providerMetadataIdentifier.getIdentifierKey(), JsonUtils.toJson(serviceDefinition));
}
@Override
public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {}
@Override
public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {}
@Override
public void saveSubscribedData(
SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {}
@Override
public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
return null;
}
@Override
public void destroy() {}
@Override
public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return null;
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {}
@Override
public boolean shouldReportDefinition() {
return true;
}
@Override
public boolean shouldReportMetadata() {
return false;
}
@Override
public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) {
return null;
}
@Override
public void storeConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, Map serviceParameterMap) {
store.put(consumerMetadataIdentifier.getIdentifierKey(), JsonUtils.toJson(serviceParameterMap));
}
Map<String, String> store = new ConcurrentHashMap<>();
};
}
};
@Test
void testGetOneMetadataReport() {
URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url);
MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url);
Assertions.assertEquals(metadataReport1, metadataReport2);
}
@Test
void testGetOneMetadataReportForIpFormat() {
String hostName = NetUtils.getLocalAddress().getHostName();
String ip = NetUtils.getIpByHost(hostName);
URL url1 = URL.valueOf(
"zookeeper://" + hostName + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
URL url2 =
URL.valueOf("zookeeper://" + ip + ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
Assertions.assertEquals(metadataReport1, metadataReport2);
}
@Test
void testGetForDiffService() {
URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic");
URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic");
MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
Assertions.assertEquals(metadataReport1, metadataReport2);
}
@Test
void testGetForDiffGroup() {
URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=aaa");
URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&group=bbb");
MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
Assertions.assertNotEquals(metadataReport1, metadataReport2);
}
@Test
void testGetForSameNamespace() {
URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService1?version=1.0.0&application=vic&namespace=test");
URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService2?version=1.0.0&application=vic&namespace=test");
MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
Assertions.assertEquals(metadataReport1, metadataReport2);
}
@Test
void testGetForDiffNamespace() {
URL url1 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&namespace=test");
URL url2 = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&namespace=dev");
MetadataReport metadataReport1 = metadataReportFactory.getMetadataReport(url1);
MetadataReport metadataReport2 = metadataReportFactory.getMetadataReport(url2);
Assertions.assertNotEquals(metadataReport1, metadataReport2);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AbstractMetadataReportTest {
private static final Logger logger = LoggerFactory.getLogger(AbstractMetadataReportTest.class);
private NewMetadataReport abstractMetadataReport;
private ApplicationModel applicationModel;
@BeforeEach
public void before() {
// set the simple name of current class as the application name
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
applicationModel = frameworkModel.newApplication();
applicationModel
.getApplicationConfigManager()
.setApplication(new ApplicationConfig(getClass().getSimpleName()));
URL url = URL.valueOf("zookeeper://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&sync=true");
abstractMetadataReport = new NewMetadataReport(url, applicationModel);
}
@AfterEach
public void reset() {
// reset
ApplicationModel.reset();
}
@Test
void testGetProtocol() {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&side=provider");
String protocol = abstractMetadataReport.getProtocol(url);
assertEquals("provider", protocol);
URL url2 = URL.valueOf("consumer://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic");
String protocol2 = abstractMetadataReport.getProtocol(url2);
assertEquals("consumer", protocol2);
}
@Test
void testStoreProviderUsual() throws ClassNotFoundException {
String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService";
String version = "1.0.0";
String group = null;
String application = "vic";
ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) abstractMetadataReport.getReportCacheExecutor();
long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount();
MetadataIdentifier providerMetadataIdentifier =
storeProvider(abstractMetadataReport, interfaceName, version, group, application);
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1);
Assertions.assertNotNull(
abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)));
}
@Test
void testStoreProviderSync() throws ClassNotFoundException {
String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService";
String version = "1.0.0";
String group = null;
String application = "vic";
abstractMetadataReport.syncReport = true;
MetadataIdentifier providerMetadataIdentifier =
storeProvider(abstractMetadataReport, interfaceName, version, group, application);
Assertions.assertNotNull(
abstractMetadataReport.store.get(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)));
}
@Test
void testFileExistAfterPut() throws ClassNotFoundException {
// just for one method
String filePath = System.getProperty("user.home") + "/dubbo-md-unit.properties";
URL singleUrl = URL.valueOf("redis://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.metadata.store.InterfaceNameTestService?version=1.0.0&application=singleTest&sync=true&file="
+ filePath);
NewMetadataReport singleMetadataReport = new NewMetadataReport(singleUrl, applicationModel);
assertFalse(singleMetadataReport.file.exists());
String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService";
String version = "1.0.0";
String group = null;
String application = "vic";
ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) singleMetadataReport.getReportCacheExecutor();
long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount();
MetadataIdentifier providerMetadataIdentifier =
storeProvider(singleMetadataReport, interfaceName, version, group, application);
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1);
assertTrue(singleMetadataReport.file.exists());
assertTrue(singleMetadataReport.properties.containsKey(
providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)));
}
@Test
void testRetry() throws ClassNotFoundException {
String interfaceName = "org.apache.dubbo.metadata.store.RetryTestService";
String version = "1.0.0.retry";
String group = null;
String application = "vic.retry";
URL storeUrl = URL.valueOf("retryReport://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestServiceForRetry?version=1.0.0.retry&application=vic.retry&sync=true");
RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel);
retryReport.metadataReportRetry.retryPeriod = 400L;
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestService?version=1.0.0&application=vic&sync=true");
Assertions.assertNull(retryReport.metadataReportRetry.retryScheduledFuture);
assertEquals(0, retryReport.metadataReportRetry.retryCounter.get());
assertTrue(retryReport.store.isEmpty());
assertTrue(retryReport.failedReports.isEmpty());
ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) retryReport.getReportCacheExecutor();
ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor)
retryReport.getMetadataReportRetry().getRetryExecutor();
long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount();
long completedTaskCount2 = retryExecutor.getCompletedTaskCount();
storeProvider(retryReport, interfaceName, version, group, application);
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1);
assertTrue(retryReport.store.isEmpty());
assertFalse(retryReport.failedReports.isEmpty());
assertNotNull(retryReport.metadataReportRetry.retryScheduledFuture);
await().until(() -> retryExecutor.getCompletedTaskCount() > completedTaskCount2 + 2);
assertNotEquals(0, retryReport.metadataReportRetry.retryCounter.get());
assertTrue(retryReport.metadataReportRetry.retryCounter.get() >= 3);
assertFalse(retryReport.store.isEmpty());
assertTrue(retryReport.failedReports.isEmpty());
}
@Test
void testRetryCancel() throws ClassNotFoundException {
String interfaceName = "org.apache.dubbo.metadata.store.RetryTestService";
String version = "1.0.0.retrycancel";
String group = null;
String application = "vic.retry";
URL storeUrl = URL.valueOf(
"retryReport://" + NetUtils.getLocalAddress().getHostName()
+ ":4444/org.apache.dubbo.TestServiceForRetryCancel?version=1.0.0.retrycancel&application=vic.retry&sync=true");
RetryMetadataReport retryReport = new RetryMetadataReport(storeUrl, 2, applicationModel);
retryReport.metadataReportRetry.retryPeriod = 150L;
retryReport.metadataReportRetry.retryTimesIfNonFail = 2;
retryReport.semaphore = new Semaphore(1);
ScheduledThreadPoolExecutor retryExecutor = (ScheduledThreadPoolExecutor)
retryReport.getMetadataReportRetry().getRetryExecutor();
long completedTaskCount = retryExecutor.getCompletedTaskCount();
storeProvider(retryReport, interfaceName, version, group, application);
// Wait for the assignment of retryScheduledFuture to complete
await().until(() -> retryReport.metadataReportRetry.retryScheduledFuture != null);
assertFalse(retryReport.metadataReportRetry.retryScheduledFuture.isCancelled());
assertFalse(retryReport.metadataReportRetry.retryExecutor.isShutdown());
retryReport.semaphore.release(2);
await().until(() -> retryExecutor.getCompletedTaskCount() > completedTaskCount + 2);
await().untilAsserted(() -> assertTrue(retryReport.metadataReportRetry.retryScheduledFuture.isCancelled()));
await().untilAsserted(() -> assertTrue(retryReport.metadataReportRetry.retryExecutor.isShutdown()));
}
private MetadataIdentifier storeProvider(
AbstractMetadataReport abstractMetadataReport,
String interfaceName,
String version,
String group,
String application)
throws ClassNotFoundException {
URL url = URL.valueOf(
"xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version
+ "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=8989");
MetadataIdentifier providerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application);
Class interfaceClass = Class.forName(interfaceName);
FullServiceDefinition fullServiceDefinition =
ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters());
abstractMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition);
return providerMetadataIdentifier;
}
private MetadataIdentifier storeConsumer(
AbstractMetadataReport abstractMetadataReport,
String interfaceName,
String version,
String group,
String application,
Map<String, String> tmp) {
URL url = URL.valueOf(
"xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + "?version=" + version
+ "&application=" + application + (group == null ? "" : "&group=" + group) + "&testPKey=9090");
tmp.putAll(url.getParameters());
MetadataIdentifier consumerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application);
abstractMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp);
return consumerMetadataIdentifier;
}
@Test
void testPublishAll() throws ClassNotFoundException {
ThreadPoolExecutor reportCacheExecutor = (ThreadPoolExecutor) abstractMetadataReport.getReportCacheExecutor();
assertTrue(abstractMetadataReport.store.isEmpty());
assertTrue(abstractMetadataReport.allMetadataReports.isEmpty());
String interfaceName = "org.apache.dubbo.metadata.store.InterfaceNameTestService";
String version = "1.0.0";
String group = null;
String application = "vic";
long completedTaskCount1 = reportCacheExecutor.getCompletedTaskCount();
MetadataIdentifier providerMetadataIdentifier1 =
storeProvider(abstractMetadataReport, interfaceName, version, group, application);
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount1);
assertEquals(1, abstractMetadataReport.allMetadataReports.size());
assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier1))
.getParameters()
.containsKey("testPKey"));
long completedTaskCount2 = reportCacheExecutor.getCompletedTaskCount();
MetadataIdentifier providerMetadataIdentifier2 =
storeProvider(abstractMetadataReport, interfaceName, version + "_2", group + "_2", application);
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount2);
assertEquals(2, abstractMetadataReport.allMetadataReports.size());
assertTrue(((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2))
.getParameters()
.containsKey("testPKey"));
assertEquals(
((FullServiceDefinition) abstractMetadataReport.allMetadataReports.get(providerMetadataIdentifier2))
.getParameters()
.get("version"),
version + "_2");
Map<String, String> tmpMap = new HashMap<>();
tmpMap.put("testKey", "value");
long completedTaskCount3 = reportCacheExecutor.getCompletedTaskCount();
MetadataIdentifier consumerMetadataIdentifier =
storeConsumer(abstractMetadataReport, interfaceName, version + "_3", group + "_3", application, tmpMap);
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount3);
assertEquals(3, abstractMetadataReport.allMetadataReports.size());
Map tmpMapResult = (Map) abstractMetadataReport.allMetadataReports.get(consumerMetadataIdentifier);
assertEquals("9090", tmpMapResult.get("testPKey"));
assertEquals("value", tmpMapResult.get("testKey"));
assertEquals(3, abstractMetadataReport.store.size());
abstractMetadataReport.store.clear();
assertEquals(0, abstractMetadataReport.store.size());
long completedTaskCount4 = reportCacheExecutor.getCompletedTaskCount();
abstractMetadataReport.publishAll();
await().until(() -> reportCacheExecutor.getCompletedTaskCount() > completedTaskCount4);
assertEquals(3, abstractMetadataReport.store.size());
String v = abstractMetadataReport.store.get(providerMetadataIdentifier1.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
FullServiceDefinition data = JsonUtils.toJavaObject(v, FullServiceDefinition.class);
checkParam(data.getParameters(), application, version);
String v2 = abstractMetadataReport.store.get(providerMetadataIdentifier2.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
data = JsonUtils.toJavaObject(v2, FullServiceDefinition.class);
checkParam(data.getParameters(), application, version + "_2");
String v3 = abstractMetadataReport.store.get(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
Map v3Map = JsonUtils.toJavaObject(v3, Map.class);
checkParam(v3Map, application, version + "_3");
}
@Test
void testCalculateStartTime() {
for (int i = 0; i < 300; i++) {
long t = abstractMetadataReport.calculateStartTime() + System.currentTimeMillis();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(t);
assertTrue(c.get(Calendar.HOUR_OF_DAY) >= 2);
assertTrue(c.get(Calendar.HOUR_OF_DAY) <= 6);
}
}
private void checkParam(Map<String, String> map, String application, String version) {
assertEquals(map.get("application"), application);
assertEquals(map.get("version"), version);
}
private static class NewMetadataReport extends AbstractMetadataReport {
Map<String, String> store = new ConcurrentHashMap<>();
public NewMetadataReport(URL metadataReportURL, ApplicationModel applicationModel) {
super(metadataReportURL);
this.applicationModel = applicationModel;
}
@Override
protected void doStoreProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) {
store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString);
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
}
private static class RetryMetadataReport extends AbstractMetadataReport {
Map<String, String> store = new ConcurrentHashMap<>();
int needRetryTimes;
int executeTimes = 0;
Semaphore semaphore = new Semaphore(Integer.MAX_VALUE);
public RetryMetadataReport(URL metadataReportURL, int needRetryTimes, ApplicationModel applicationModel) {
super(metadataReportURL);
this.needRetryTimes = needRetryTimes;
this.applicationModel = applicationModel;
}
@Override
protected void doStoreProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
++executeTimes;
logger.info("***" + executeTimes + ";" + System.currentTimeMillis());
semaphore.acquireUninterruptibly();
if (executeTimes <= needRetryTimes) {
throw new RuntimeException("must retry:" + executeTimes);
}
store.put(providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString) {
++executeTimes;
if (executeTimes <= needRetryTimes) {
throw new RuntimeException("must retry:" + executeTimes);
}
store.put(consumerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), serviceParameterString);
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier metadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
public String getServiceDefinition(MetadataIdentifier consumerMetadataIdentifier) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {
throw new UnsupportedOperationException(
"This extension does not support working as a remote metadata center.");
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifierTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.apache.dubbo.metadata.MetadataConstants;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
/**
* 2019/1/7
*/
class MetadataIdentifierTest {
@Test
void testGetUniqueKey() {
String interfaceName = "org.apache.dubbo.metadata.integration.InterfaceNameTestService";
String version = "1.0.0.zk.md";
String group = null;
String application = "vic.zk.md";
MetadataIdentifier providerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application);
Assertions.assertEquals(
providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH),
"metadata" + PATH_SEPARATOR + interfaceName + PATH_SEPARATOR
+ (version == null ? "" : (version + PATH_SEPARATOR))
+ (group == null ? "" : (group + PATH_SEPARATOR)) + PROVIDER_SIDE
+ PATH_SEPARATOR + application);
Assertions.assertEquals(
providerMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY),
interfaceName
+ MetadataConstants.KEY_SEPARATOR
+ (version == null ? "" : version)
+ MetadataConstants.KEY_SEPARATOR
+ (group == null ? "" : group)
+ MetadataConstants.KEY_SEPARATOR
+ PROVIDER_SIDE
+ MetadataConstants.KEY_SEPARATOR
+ application);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnumTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnumTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@link KeyTypeEnum} Test-Cases
*
* @since 2.7.8
*/
class KeyTypeEnumTest {
/**
* {@link KeyTypeEnum#build(String, String...)}
*/
@Test
void testBuild() {
assertEquals("/A/B/C", KeyTypeEnum.PATH.build("/A", "/B", "C"));
assertEquals("A:B:C", KeyTypeEnum.UNIQUE_KEY.build("A", "B", "C"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifierTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class BaseApplicationMetadataIdentifierTest {
private BaseApplicationMetadataIdentifier baseApplicationMetadataIdentifier;
{
baseApplicationMetadataIdentifier = new BaseApplicationMetadataIdentifier();
baseApplicationMetadataIdentifier.application = "app";
}
@Test
void getUniqueKey() {
String uniqueKey = baseApplicationMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY, "reversion");
Assertions.assertEquals(uniqueKey, "app:reversion");
String uniqueKey2 = baseApplicationMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH, "reversion");
Assertions.assertEquals(uniqueKey2, "metadata/app/reversion");
}
@Test
void getIdentifierKey() {
String identifierKey = baseApplicationMetadataIdentifier.getIdentifierKey("reversion");
Assertions.assertEquals(identifierKey, "app:reversion");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java | dubbo-metadata/dubbo-metadata-api/src/test/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifierTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class BaseServiceMetadataIdentifierTest {
private BaseServiceMetadataIdentifier baseServiceMetadataIdentifier;
{
baseServiceMetadataIdentifier = new BaseServiceMetadataIdentifier();
baseServiceMetadataIdentifier.version = "1.0.0";
baseServiceMetadataIdentifier.group = "test";
baseServiceMetadataIdentifier.side = "provider";
baseServiceMetadataIdentifier.serviceInterface = "BaseServiceMetadataIdentifierTest";
}
@Test
void getUniqueKey() {
String uniqueKey = baseServiceMetadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY, "appName");
Assertions.assertEquals(uniqueKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName");
String uniqueKey2 = baseServiceMetadataIdentifier.getUniqueKey(KeyTypeEnum.PATH, "appName");
Assertions.assertEquals(uniqueKey2, "metadata/BaseServiceMetadataIdentifierTest/1.0.0/test/provider/appName");
}
@Test
void getIdentifierKey() {
String identifierKey = baseServiceMetadataIdentifier.getIdentifierKey("appName");
Assertions.assertEquals(identifierKey, "BaseServiceMetadataIdentifierTest:1.0.0:test:provider:appName");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIRequestOrBuilder.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIRequestOrBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface OpenAPIRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.OpenAPIRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return The group.
*/
String getGroup();
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return The bytes for group.
*/
com.google.protobuf.ByteString getGroupBytes();
/**
* <pre>
* The openAPI version, using a major.minor.patch versioning scheme
* e.g. 1.0.1
* </pre>
*
* <code>string version = 2;</code>
* @return The version.
*/
String getVersion();
/**
* <pre>
* The openAPI version, using a major.minor.patch versioning scheme
* e.g. 1.0.1
* </pre>
*
* <code>string version = 2;</code>
* @return The bytes for version.
*/
com.google.protobuf.ByteString getVersionBytes();
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @return A list containing the tag.
*/
java.util.List<String> getTagList();
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @return The count of tag.
*/
int getTagCount();
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @param index The index of the element to return.
* @return The tag at the given index.
*/
String getTag(int index);
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @param index The index of the value to return.
* @return The bytes of the tag at the given index.
*/
com.google.protobuf.ByteString getTagBytes(int index);
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @return A list containing the service.
*/
java.util.List<String> getServiceList();
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @return The count of service.
*/
int getServiceCount();
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @param index The index of the element to return.
* @return The service at the given index.
*/
String getService(int index);
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @param index The index of the value to return.
* @return The bytes of the service at the given index.
*/
com.google.protobuf.ByteString getServiceBytes(int index);
/**
* <pre>
* The openAPI specification version, using a major.minor.patch versioning scheme
* e.g. 3.0.1, 3.1.0
* The default value is '3.0.1'.
* </pre>
*
* <code>string openapi = 5;</code>
* @return The openapi.
*/
String getOpenapi();
/**
* <pre>
* The openAPI specification version, using a major.minor.patch versioning scheme
* e.g. 3.0.1, 3.1.0
* The default value is '3.0.1'.
* </pre>
*
* <code>string openapi = 5;</code>
* @return The bytes for openapi.
*/
com.google.protobuf.ByteString getOpenapiBytes();
/**
* <pre>
* The format of the response.
* The default value is 'JSON'.
* </pre>
*
* <code>optional .org.apache.dubbo.metadata.OpenAPIFormat format = 6;</code>
* @return Whether the format field is set.
*/
boolean hasFormat();
/**
* <pre>
* The format of the response.
* The default value is 'JSON'.
* </pre>
*
* <code>optional .org.apache.dubbo.metadata.OpenAPIFormat format = 6;</code>
* @return The enum numeric value on the wire for format.
*/
int getFormatValue();
/**
* <pre>
* The format of the response.
* The default value is 'JSON'.
* </pre>
*
* <code>optional .org.apache.dubbo.metadata.OpenAPIFormat format = 6;</code>
* @return The format.
*/
OpenAPIFormat getFormat();
/**
* <pre>
* Whether to pretty print for json.
* The default value is 'false'.
* </pre>
*
* <code>optional bool pretty = 7;</code>
* @return Whether the pretty field is set.
*/
boolean hasPretty();
/**
* <pre>
* Whether to pretty print for json.
* The default value is 'false'.
* </pre>
*
* <code>optional bool pretty = 7;</code>
* @return The pretty.
*/
boolean getPretty();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataRequest.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* <pre>
* Metadata request message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.MetadataRequest}
*/
public final class MetadataRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.MetadataRequest)
MetadataRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MetadataRequest.newBuilder() to construct.
private MetadataRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MetadataRequest() {
revision_ = "";
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new MetadataRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataRequest_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(MetadataRequest.class, Builder.class);
}
public static final int REVISION_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile Object revision_ = "";
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return The revision.
*/
@Override
public String getRevision() {
Object ref = revision_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
revision_ = s;
return s;
}
}
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return The bytes for revision.
*/
@Override
public com.google.protobuf.ByteString getRevisionBytes() {
Object ref = revision_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
revision_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(revision_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, revision_);
}
getUnknownFields().writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(revision_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, revision_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MetadataRequest)) {
return super.equals(obj);
}
MetadataRequest other = (MetadataRequest) obj;
if (!getRevision().equals(other.getRevision())) {
return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + REVISION_FIELD_NUMBER;
hash = (53 * hash) + getRevision().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static MetadataRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static MetadataRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static MetadataRequest parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static MetadataRequest parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static MetadataRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static MetadataRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static MetadataRequest parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static MetadataRequest 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 MetadataRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static MetadataRequest 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 MetadataRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static MetadataRequest parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(MetadataRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Metadata request message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.MetadataRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.MetadataRequest)
MetadataRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataRequest_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass
.internal_static_org_apache_dubbo_metadata_MetadataRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(MetadataRequest.class, Builder.class);
}
// Construct using org.apache.dubbo.metadata.MetadataRequest.newBuilder()
private Builder() {}
private Builder(BuilderParent parent) {
super(parent);
}
@Override
public Builder clear() {
super.clear();
bitField0_ = 0;
revision_ = "";
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataRequest_descriptor;
}
@Override
public MetadataRequest getDefaultInstanceForType() {
return MetadataRequest.getDefaultInstance();
}
@Override
public MetadataRequest build() {
MetadataRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public MetadataRequest buildPartial() {
MetadataRequest result = new MetadataRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(MetadataRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.revision_ = revision_;
}
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof MetadataRequest) {
return mergeFrom((MetadataRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(MetadataRequest other) {
if (other == MetadataRequest.getDefaultInstance()) {
return this;
}
if (!other.getRevision().isEmpty()) {
revision_ = other.revision_;
bitField0_ |= 0x00000001;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
revision_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private Object revision_ = "";
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return The revision.
*/
public String getRevision() {
Object ref = revision_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
revision_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return The bytes for revision.
*/
public com.google.protobuf.ByteString getRevisionBytes() {
Object ref = revision_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
revision_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @param value The revision to set.
* @return This builder for chaining.
*/
public Builder setRevision(String value) {
if (value == null) {
throw new NullPointerException();
}
revision_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return This builder for chaining.
*/
public Builder clearRevision() {
revision_ = getDefaultInstance().getRevision();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @param value The bytes for revision to set.
* @return This builder for chaining.
*/
public Builder setRevisionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
revision_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
@Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@Override
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.MetadataRequest)
}
// @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.MetadataRequest)
private static final MetadataRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new MetadataRequest();
}
public static MetadataRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MetadataRequest> PARSER =
new com.google.protobuf.AbstractParser<MetadataRequest>() {
@Override
public MetadataRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<MetadataRequest> parser() {
return PARSER;
}
@Override
public com.google.protobuf.Parser<MetadataRequest> getParserForType() {
return PARSER;
}
@Override
public MetadataRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIInfoOrBuilder.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIInfoOrBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface OpenAPIInfoOrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.OpenAPIInfo)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return The definition.
*/
String getDefinition();
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return The bytes for definition.
*/
com.google.protobuf.ByteString getDefinitionBytes();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.beans.Transient;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.DOT_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.IS_EXTRA;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
public class MetadataInfo implements Serializable {
public static final MetadataInfo EMPTY = new MetadataInfo();
private static final Logger logger = LoggerFactory.getLogger(MetadataInfo.class);
private String app;
// revision that will report to registry or remote meta center, must always update together with rawMetadataInfo,
// check {@link this#calAndGetRevision}
private volatile String revision;
// key format is '{group}/{interface name}:{version}:{protocol}'
private final Map<String, ServiceInfo> services;
/* used at runtime */
private transient AtomicBoolean initiated = new AtomicBoolean(false);
// Json formatted metadata that will report to remote meta center, must always update together with revision, check
// {@link this#calAndGetRevision}
private transient volatile String rawMetadataInfo;
// key format is '{group}/{interface name}:{version}'
private transient Map<String, Set<ServiceInfo>> subscribedServices;
private final transient Map<String, String> extendParams;
private final transient Map<String, String> instanceParams;
protected transient volatile boolean updated = false;
private transient ConcurrentNavigableMap<String, SortedSet<URL>> subscribedServiceURLs;
private transient ConcurrentNavigableMap<String, SortedSet<URL>> exportedServiceURLs;
private transient ExtensionLoader<MetadataParamsFilter> loader;
public MetadataInfo() {
this(null);
}
public MetadataInfo(String app) {
this(app, null, null);
}
public MetadataInfo(String app, String revision, Map<String, ServiceInfo> services) {
this.app = app;
this.revision = revision;
this.services = services == null ? new ConcurrentHashMap<>() : services;
this.extendParams = new ConcurrentHashMap<>();
this.instanceParams = new ConcurrentHashMap<>();
}
private MetadataInfo(
String app,
String revision,
Map<String, ServiceInfo> services,
AtomicBoolean initiated,
Map<String, String> extendParams,
Map<String, String> instanceParams,
boolean updated,
ConcurrentNavigableMap<String, SortedSet<URL>> subscribedServiceURLs,
ConcurrentNavigableMap<String, SortedSet<URL>> exportedServiceURLs,
ExtensionLoader<MetadataParamsFilter> loader) {
this.app = app;
this.revision = revision;
this.services = new ConcurrentHashMap<>(services);
this.initiated = new AtomicBoolean(initiated.get());
this.extendParams = new ConcurrentHashMap<>(extendParams);
this.instanceParams = new ConcurrentHashMap<>(instanceParams);
this.updated = updated;
this.subscribedServiceURLs =
subscribedServiceURLs == null ? null : new ConcurrentSkipListMap<>(subscribedServiceURLs);
this.exportedServiceURLs =
exportedServiceURLs == null ? null : new ConcurrentSkipListMap<>(exportedServiceURLs);
this.loader = loader;
}
/**
* Initialize is needed when MetadataInfo is created from deserialization on the consumer side before being used for RPC call.
*/
public void init() {
if (!initiated.compareAndSet(false, true)) {
return;
}
if (CollectionUtils.isNotEmptyMap(services)) {
services.forEach((_k, serviceInfo) -> {
serviceInfo.init();
// create duplicate serviceKey(without protocol)->serviceInfo mapping to support metadata search when
// protocol is not specified on consumer side.
if (subscribedServices == null) {
subscribedServices = new HashMap<>();
}
Set<ServiceInfo> serviceInfos =
subscribedServices.computeIfAbsent(serviceInfo.getServiceKey(), _key -> new HashSet<>());
serviceInfos.add(serviceInfo);
});
}
}
public synchronized void addService(URL url) {
// fixme, pass in application mode context during initialization of MetadataInfo.
if (this.loader == null) {
this.loader = url.getOrDefaultApplicationModel().getExtensionLoader(MetadataParamsFilter.class);
}
List<MetadataParamsFilter> filters = loader.getActivateExtension(url, "params-filter");
// generate service level metadata
ServiceInfo serviceInfo = new ServiceInfo(url, filters);
this.services.put(serviceInfo.getMatchKey(), serviceInfo);
// extract common instance level params
extractInstanceParams(url, filters);
if (exportedServiceURLs == null) {
exportedServiceURLs = new ConcurrentSkipListMap<>();
}
addURL(exportedServiceURLs, url);
updated = true;
}
public synchronized void removeService(URL url) {
if (url == null) {
return;
}
this.services.remove(url.getProtocolServiceKey());
if (exportedServiceURLs != null) {
removeURL(exportedServiceURLs, url);
}
updated = true;
}
public String getRevision() {
return revision;
}
/**
* Calculation of this instance's status like revision and modification of the same instance must be synchronized among different threads.
* <p>
* Usage of this method is strictly restricted to certain points such as when during registration. Always try to use {@link this#getRevision()} instead.
*/
public synchronized String calAndGetRevision() {
if (revision != null && !updated) {
return revision;
}
updated = false;
if (CollectionUtils.isEmptyMap(services)) {
this.revision = EMPTY_REVISION;
} else {
String tempRevision = calRevision();
if (!StringUtils.isEquals(this.revision, tempRevision)) {
if (logger.isInfoEnabled()) {
logger.info(String.format(
"[METADATA_REGISTER] metadata revision changed: %s -> %s, app: %s, services: %d",
this.revision, tempRevision, this.app, this.services.size()));
}
this.revision = tempRevision;
this.rawMetadataInfo = JsonUtils.toJson(this);
}
}
return revision;
}
public synchronized String calRevision() {
StringBuilder sb = new StringBuilder();
sb.append(app);
for (Map.Entry<String, ServiceInfo> entry : new TreeMap<>(services).entrySet()) {
sb.append(entry.getValue().toDescString());
}
return RevisionResolver.calRevision(sb.toString());
}
public void setRevision(String revision) {
this.revision = revision;
}
@Transient
public String getContent() {
return this.rawMetadataInfo;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public Map<String, ServiceInfo> getServices() {
return services;
}
/**
* Get service info of an interface with specified group, version and protocol
* @param protocolServiceKey key is of format '{group}/{interface name}:{version}:{protocol}'
* @return the specific service info related to protocolServiceKey
*/
public ServiceInfo getServiceInfo(String protocolServiceKey) {
return services.get(protocolServiceKey);
}
/**
* Get service infos of an interface with specified group, version.
* There may have several service infos of different protocols, this method will simply pick the first one.
*
* @param serviceKeyWithoutProtocol key is of format '{group}/{interface name}:{version}'
* @return the first service info related to serviceKey
*/
public ServiceInfo getNoProtocolServiceInfo(String serviceKeyWithoutProtocol) {
if (CollectionUtils.isEmptyMap(subscribedServices)) {
return null;
}
Set<ServiceInfo> subServices = subscribedServices.get(serviceKeyWithoutProtocol);
if (CollectionUtils.isNotEmpty(subServices)) {
List<ServiceInfo> validServices = subServices.stream()
.filter(serviceInfo -> StringUtils.isEmpty(serviceInfo.getParameter(IS_EXTRA)))
.collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(validServices)) {
return validServices.iterator().next();
} else {
return subServices.iterator().next();
}
}
return null;
}
public ServiceInfo getValidServiceInfo(String serviceKey) {
ServiceInfo serviceInfo = getServiceInfo(serviceKey);
if (serviceInfo == null) {
serviceInfo = getNoProtocolServiceInfo(serviceKey);
if (serviceInfo == null) {
return null;
}
}
return serviceInfo;
}
public List<ServiceInfo> getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) {
return getServices().values().stream()
.filter(serviceInfo -> serviceInfo.matchProtocolServiceKey(consumerProtocolServiceKey))
.collect(Collectors.toList());
}
public Map<String, String> getExtendParams() {
return extendParams;
}
public Map<String, String> getInstanceParams() {
return instanceParams;
}
public String getParameter(String key, String serviceKey) {
ServiceInfo serviceInfo = getValidServiceInfo(serviceKey);
if (serviceInfo == null) {
return null;
}
return serviceInfo.getParameter(key);
}
public Map<String, String> getParameters(String serviceKey) {
ServiceInfo serviceInfo = getValidServiceInfo(serviceKey);
if (serviceInfo == null) {
return Collections.emptyMap();
}
return serviceInfo.getAllParams();
}
public String getServiceString(String protocolServiceKey) {
if (protocolServiceKey == null) {
return null;
}
ServiceInfo serviceInfo = getValidServiceInfo(protocolServiceKey);
if (serviceInfo == null) {
return null;
}
return serviceInfo.toFullString();
}
public synchronized void addSubscribedURL(URL url) {
if (subscribedServiceURLs == null) {
subscribedServiceURLs = new ConcurrentSkipListMap<>();
}
addURL(subscribedServiceURLs, url);
}
public boolean removeSubscribedURL(URL url) {
if (subscribedServiceURLs == null) {
return true;
}
return removeURL(subscribedServiceURLs, url);
}
public ConcurrentNavigableMap<String, SortedSet<URL>> getSubscribedServiceURLs() {
return subscribedServiceURLs;
}
public ConcurrentNavigableMap<String, SortedSet<URL>> getExportedServiceURLs() {
return exportedServiceURLs;
}
public Set<URL> collectExportedURLSet() {
if (exportedServiceURLs == null) {
return Collections.emptySet();
}
return exportedServiceURLs.values().stream()
.filter(CollectionUtils::isNotEmpty)
.flatMap(Collection::stream)
.collect(Collectors.toSet());
}
private boolean addURL(Map<String, SortedSet<URL>> serviceURLs, URL url) {
SortedSet<URL> urls = serviceURLs.computeIfAbsent(url.getServiceKey(), this::newSortedURLs);
// make sure the parameters of tmpUrl is variable
return urls.add(url);
}
boolean removeURL(Map<String, SortedSet<URL>> serviceURLs, URL url) {
String key = url.getServiceKey();
SortedSet<URL> urls = serviceURLs.getOrDefault(key, null);
if (urls == null) {
return true;
}
boolean r = urls.remove(url);
// if it is empty
if (urls.isEmpty()) {
serviceURLs.remove(key);
}
return r;
}
private SortedSet<URL> newSortedURLs(String serviceKey) {
return new TreeSet<>(URLComparator.INSTANCE);
}
@Override
public int hashCode() {
return Objects.hash(app, services);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MetadataInfo)) {
return false;
}
MetadataInfo other = (MetadataInfo) obj;
return Objects.equals(app, other.getApp())
&& ((services == null && other.services == null)
|| (services != null && services.equals(other.services)));
}
private void extractInstanceParams(URL url, List<MetadataParamsFilter> filters) {
if (CollectionUtils.isEmpty(filters)) {
return;
}
String[] included, excluded;
if (filters.size() == 1) {
MetadataParamsFilter filter = filters.get(0);
included = filter.instanceParamsIncluded();
excluded = filter.instanceParamsExcluded();
} else {
Set<String> includedList = new HashSet<>();
Set<String> excludedList = new HashSet<>();
filters.forEach(filter -> {
if (ArrayUtils.isNotEmpty(filter.instanceParamsIncluded())) {
includedList.addAll(Arrays.asList(filter.instanceParamsIncluded()));
}
if (ArrayUtils.isNotEmpty(filter.instanceParamsExcluded())) {
excludedList.addAll(Arrays.asList(filter.instanceParamsExcluded()));
}
});
included = includedList.toArray(new String[0]);
excluded = excludedList.toArray(new String[0]);
}
Map<String, String> tmpInstanceParams = new HashMap<>();
if (ArrayUtils.isNotEmpty(included)) {
for (String p : included) {
String value = url.getParameter(p);
if (value != null) {
tmpInstanceParams.put(p, value);
}
}
} else if (ArrayUtils.isNotEmpty(excluded)) {
tmpInstanceParams.putAll(url.getParameters());
for (String p : excluded) {
tmpInstanceParams.remove(p);
}
}
tmpInstanceParams.forEach((key, value) -> {
String oldValue = instanceParams.put(key, value);
if (!TIMESTAMP_KEY.equals(key) && oldValue != null && !oldValue.equals(value)) {
throw new IllegalStateException(String.format(
"Inconsistent instance metadata found in different services: %s, %s", oldValue, value));
}
});
}
@Override
public String toString() {
return "metadata{" + "app='"
+ app + "'," + "revision='"
+ revision + "'," + "size="
+ (services == null ? 0 : services.size()) + "," + "services="
+ getSimplifiedServices(services) + "}";
}
public String toFullString() {
return "metadata{" + "app='" + app + "'," + "revision='" + revision + "'," + "services=" + services + "}";
}
private String getSimplifiedServices(Map<String, ServiceInfo> services) {
if (services == null) {
return "[]";
}
return services.keySet().toString();
}
@Override
public synchronized MetadataInfo clone() {
return new MetadataInfo(
app,
revision,
services,
initiated,
extendParams,
instanceParams,
updated,
subscribedServiceURLs,
exportedServiceURLs,
loader);
}
private Object readResolve() {
// create a new object from the deserialized one, in order to call constructor
return new MetadataInfo(this.app, this.revision, this.services);
}
public static class ServiceInfo implements Serializable {
private String name;
private String group;
private String version;
private String protocol;
private int port = -1;
private String path; // most of the time, path is the same with the interface name.
private Map<String, String> params;
// params configured on consumer side,
private transient volatile Map<String, String> consumerParams;
// cached method params
private transient volatile Map<String, Map<String, String>> methodParams;
private transient volatile Map<String, Map<String, String>> consumerMethodParams;
// cached numbers
private transient volatile Map<String, Number> numbers;
private transient volatile Map<String, Map<String, Number>> methodNumbers;
// service + group + version
private transient volatile String serviceKey;
// service + group + version + protocol
private transient volatile String matchKey;
private transient volatile ProtocolServiceKey protocolServiceKey;
private transient URL url;
public ServiceInfo() {}
public ServiceInfo(URL url, List<MetadataParamsFilter> filters) {
this(
url.getServiceInterface(),
url.getGroup(),
url.getVersion(),
url.getProtocol(),
url.getPort(),
url.getPath(),
null);
this.url = url;
Map<String, String> params = extractServiceParams(url, filters);
// initialize method params caches.
this.methodParams = URLParam.initMethodParameters(params);
this.consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
public ServiceInfo(
String name,
String group,
String version,
String protocol,
int port,
String path,
Map<String, String> params) {
this.name = name;
this.group = group;
this.version = version;
this.protocol = protocol;
this.port = port;
this.path = path;
this.params = params == null ? new ConcurrentHashMap<>() : params;
this.serviceKey = buildServiceKey(name, group, version);
this.matchKey = buildMatchKey();
}
private Map<String, String> extractServiceParams(URL url, List<MetadataParamsFilter> filters) {
Map<String, String> params = new HashMap<>();
if (CollectionUtils.isEmpty(filters)) {
params.putAll(url.getParameters());
this.params = params;
return params;
}
String[] included, excluded;
if (filters.size() == 1) {
included = filters.get(0).serviceParamsIncluded();
excluded = filters.get(0).serviceParamsExcluded();
} else {
Set<String> includedList = new HashSet<>();
Set<String> excludedList = new HashSet<>();
for (MetadataParamsFilter filter : filters) {
if (ArrayUtils.isNotEmpty(filter.serviceParamsIncluded())) {
includedList.addAll(Arrays.asList(filter.serviceParamsIncluded()));
}
if (ArrayUtils.isNotEmpty(filter.serviceParamsExcluded())) {
excludedList.addAll(Arrays.asList(filter.serviceParamsExcluded()));
}
}
included = includedList.toArray(new String[0]);
excluded = excludedList.toArray(new String[0]);
}
if (ArrayUtils.isNotEmpty(included)) {
String[] methods = url.getParameter(METHODS_KEY, (String[]) null);
for (String p : included) {
String value = url.getParameter(p);
if (StringUtils.isNotEmpty(value) && params.get(p) == null) {
params.put(p, value);
}
appendMethodParams(url, params, methods, p);
}
} else if (ArrayUtils.isNotEmpty(excluded)) {
for (Map.Entry<String, String> entry : url.getParameters().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
boolean shouldAdd = true;
for (String excludeKey : excluded) {
if (key.equalsIgnoreCase(excludeKey) || key.contains("." + excludeKey)) {
shouldAdd = false;
break;
}
}
if (shouldAdd) {
params.put(key, value);
}
}
}
this.params = params;
return params;
}
private void appendMethodParams(URL url, Map<String, String> params, String[] methods, String p) {
if (methods != null) {
for (String method : methods) {
String mValue = url.getMethodParameterStrict(method, p);
if (StringUtils.isNotEmpty(mValue)) {
params.put(method + DOT_SEPARATOR + p, mValue);
}
}
}
}
/**
* Initialize necessary caches right after deserialization on the consumer side
*/
protected void init() {
buildMatchKey();
buildServiceKey(name, group, version);
// init method params
this.methodParams = URLParam.initMethodParameters(params);
// Actually, consumer params is empty after deserialized on the consumer side, so no need to initialize.
// Check how InstanceAddressURL operates on consumer url for more detail.
// this.consumerMethodParams = URLParam.initMethodParameters(consumerParams);
// no need to init numbers for it's only for cache purpose
}
public String getMatchKey() {
if (matchKey != null) {
return matchKey;
}
buildMatchKey();
return matchKey;
}
private String buildMatchKey() {
matchKey = getServiceKey();
if (StringUtils.isNotEmpty(protocol)) {
matchKey = getServiceKey() + GROUP_CHAR_SEPARATOR + protocol;
}
return matchKey;
}
public boolean matchProtocolServiceKey(ProtocolServiceKey protocolServiceKey) {
return ProtocolServiceKey.Matcher.isMatch(protocolServiceKey, getProtocolServiceKey());
}
public ProtocolServiceKey getProtocolServiceKey() {
if (protocolServiceKey != null) {
return protocolServiceKey;
}
protocolServiceKey = new ProtocolServiceKey(name, version, group, protocol);
return protocolServiceKey;
}
private String buildServiceKey(String name, String group, String version) {
this.serviceKey = URL.buildKey(name, group, version);
return this.serviceKey;
}
public String getServiceKey() {
if (serviceKey != null) {
return serviceKey;
}
buildServiceKey(name, group, version);
return serviceKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Map<String, String> getParams() {
if (params == null) {
return Collections.emptyMap();
}
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
@Transient
public Map<String, String> getAllParams() {
if (consumerParams != null) {
Map<String, String> allParams =
new HashMap<>((int) ((params.size() + consumerParams.size()) / 0.75f + 1));
allParams.putAll(params);
allParams.putAll(consumerParams);
return allParams;
}
return params;
}
public String getParameter(String key) {
if (consumerParams != null) {
String value = consumerParams.get(key);
if (value != null) {
return value;
}
}
return params.get(key);
}
public String getMethodParameter(String method, String key, String defaultValue) {
String value = getMethodParameter(method, key, consumerMethodParams);
if (value != null) {
return value;
}
value = getMethodParameter(method, key, methodParams);
return value == null ? defaultValue : value;
}
private String getMethodParameter(String method, String key, Map<String, Map<String, String>> map) {
String value = null;
if (map == null) {
return value;
}
Map<String, String> keyMap = map.get(method);
if (keyMap != null) {
value = keyMap.get(key);
}
return value;
}
public boolean hasMethodParameter(String method, String key) {
String value = this.getMethodParameter(method, key, (String) null);
return StringUtils.isNotEmpty(value);
}
public boolean hasMethodParameter(String method) {
return (consumerMethodParams != null && consumerMethodParams.containsKey(method))
|| (methodParams != null && methodParams.containsKey(method));
}
public String toDescString() {
return this.getMatchKey() + port + path + new TreeMap<>(getParams());
}
public void addParameter(String key, String value) {
if (consumerParams != null) {
this.consumerParams.put(key, value);
}
// refresh method params
consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
public void addParameterIfAbsent(String key, String value) {
if (consumerParams != null) {
this.consumerParams.putIfAbsent(key, value);
}
// refresh method params
consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
public void addConsumerParams(Map<String, String> params) {
// copy once for one service subscription
if (consumerParams == null) {
consumerParams = new ConcurrentHashMap<>(params);
// init method params
consumerMethodParams = URLParam.initMethodParameters(consumerParams);
}
}
public Map<String, Number> getNumbers() {
// concurrent initialization is tolerant
if (numbers == null) {
numbers = new ConcurrentHashMap<>();
}
return numbers;
}
public Map<String, Map<String, Number>> getMethodNumbers() {
if (methodNumbers == null) { // concurrent initialization is tolerant
methodNumbers = new ConcurrentHashMap<>();
}
return methodNumbers;
}
public URL getUrl() {
return url;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof ServiceInfo)) {
return false;
}
ServiceInfo serviceInfo = (ServiceInfo) obj;
/**
* Equals to Objects.equals(this.getMatchKey(), serviceInfo.getMatchKey()), but match key will not get initialized
* on json deserialization.
*/
return Objects.equals(this.getVersion(), serviceInfo.getVersion())
&& Objects.equals(this.getGroup(), serviceInfo.getGroup())
&& Objects.equals(this.getName(), serviceInfo.getName())
&& Objects.equals(this.getProtocol(), serviceInfo.getProtocol())
&& Objects.equals(this.getPort(), serviceInfo.getPort())
&& this.getParams().equals(serviceInfo.getParams());
}
@Override
public int hashCode() {
return Objects.hash(getVersion(), getGroup(), getName(), getProtocol(), getPort(), getParams());
}
@Override
public String toString() {
return getMatchKey();
}
public String toFullString() {
return "service{" + "name='"
+ name + "'," + "group='"
+ group + "'," + "version='"
+ version + "'," + "protocol='"
+ protocol + "'," + "port='"
+ port + "'," + "params="
+ params + "," + "}";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceDetector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
public class MetadataServiceDetector implements BuiltinServiceDetector {
@Override
public Class<?> getService() {
return MetadataService.class;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/InstanceMetadataChangedListener.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/InstanceMetadataChangedListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface InstanceMetadataChangedListener {
/**
* Call when metadata in provider side update <p/>
* Used to notify consumer to update metadata of ServiceInstance
*
* @param metadata latest metadata
*/
void onEvent(String metadata);
/**
* Echo test
* Used to check consumer still online
*/
default String echo(String msg) {
return msg;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIFormat.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIFormat.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* <pre>
* Response format enumeration.
* </pre>
*
* Protobuf enum {@code org.apache.dubbo.metadata.OpenAPIFormat}
*/
public enum OpenAPIFormat implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* JSON format.
* </pre>
*
* <code>JSON = 0;</code>
*/
JSON(0),
/**
* <pre>
* YAML format.
* </pre>
*
* <code>YAML = 1;</code>
*/
YAML(1),
/**
* <pre>
* PROTO format.
* </pre>
*
* <code>PROTO = 2;</code>
*/
PROTO(2),
UNRECOGNIZED(-1),
;
/**
* <pre>
* JSON format.
* </pre>
*
* <code>JSON = 0;</code>
*/
public static final int JSON_VALUE = 0;
/**
* <pre>
* YAML format.
* </pre>
*
* <code>YAML = 1;</code>
*/
public static final int YAML_VALUE = 1;
/**
* <pre>
* PROTO format.
* </pre>
*
* <code>PROTO = 2;</code>
*/
public static final int PROTO_VALUE = 2;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new IllegalArgumentException("Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@Deprecated
public static OpenAPIFormat valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static OpenAPIFormat forNumber(int value) {
switch (value) {
case 0:
return JSON;
case 1:
return YAML;
case 2:
return PROTO;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<OpenAPIFormat> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<OpenAPIFormat> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<OpenAPIFormat>() {
public OpenAPIFormat findValueByNumber(int number) {
return OpenAPIFormat.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new IllegalStateException("Can't get the descriptor of an unrecognized enum value.");
}
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 MetadataServiceV2OuterClass.getDescriptor().getEnumTypes().get(0);
}
private static final OpenAPIFormat[] VALUES = values();
public static OpenAPIFormat valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private OpenAPIFormat(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:org.apache.dubbo.metadata.OpenAPIFormat)
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ParameterTypesComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import java.util.Arrays;
public class ParameterTypesComparator {
private Class[] parameterTypes;
public ParameterTypesComparator(Class[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterTypesComparator that = (ParameterTypesComparator) o;
return Arrays.equals(parameterTypes, that.parameterTypes);
}
@Override
public int hashCode() {
return Arrays.hashCode(parameterTypes);
}
public static ParameterTypesComparator getInstance(Class[] parameterTypes) {
return new ParameterTypesComparator(parameterTypes);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingCacheManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_MAPPING_CACHE_ENTRYSIZE;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_MAPPING_CACHE_FILENAME;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_MAPPING_CACHE_FILEPATH;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_MAPPING_CACHE_MAXFILESIZE;
/**
* TODO, Using randomly accessible file-based cache can be another choice if memory consumption turns to be an issue.
*/
public class MappingCacheManager extends AbstractCacheManager<Set<String>> {
private static final String DEFAULT_FILE_NAME = ".mapping";
private static final int DEFAULT_ENTRY_SIZE = 10000;
public static MappingCacheManager getInstance(ScopeModel scopeModel) {
return scopeModel.getBeanFactory().getOrRegisterBean(MappingCacheManager.class);
}
public MappingCacheManager(boolean enableFileCache, String name, ScheduledExecutorService executorService) {
String filePath = SystemPropertyConfigUtils.getSystemProperty(DUBBO_MAPPING_CACHE_FILEPATH);
String fileName = SystemPropertyConfigUtils.getSystemProperty(DUBBO_MAPPING_CACHE_FILENAME);
if (StringUtils.isEmpty(fileName)) {
fileName = DEFAULT_FILE_NAME;
}
if (StringUtils.isNotEmpty(name)) {
fileName = fileName + "." + name;
}
String rawEntrySize = SystemPropertyConfigUtils.getSystemProperty(DUBBO_MAPPING_CACHE_ENTRYSIZE);
int entrySize = StringUtils.parseInteger(rawEntrySize);
entrySize = (entrySize == 0 ? DEFAULT_ENTRY_SIZE : entrySize);
String rawMaxFileSize = SystemPropertyConfigUtils.getSystemProperty(DUBBO_MAPPING_CACHE_MAXFILESIZE);
long maxFileSize = StringUtils.parseLong(rawMaxFileSize);
init(enableFileCache, filePath, fileName, entrySize, maxFileSize, 50, executorService);
}
@Override
protected Set<String> toValueType(String value) {
return new HashSet<>(JsonUtils.toJavaList(value, String.class));
}
@Override
protected String getName() {
return "mapping";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceInfoV2.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceInfoV2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* <pre>
* Service information message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.ServiceInfoV2}
*/
public final class ServiceInfoV2 extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.ServiceInfoV2)
ServiceInfoV2OrBuilder {
private static final long serialVersionUID = 0L;
// Use ServiceInfoV2.newBuilder() to construct.
private ServiceInfoV2(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ServiceInfoV2() {
name_ = "";
group_ = "";
version_ = "";
protocol_ = "";
path_ = "";
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new ServiceInfoV2();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor;
}
@SuppressWarnings({"rawtypes"})
@Override
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 7:
return internalGetParams();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_ServiceInfoV2_fieldAccessorTable
.ensureFieldAccessorsInitialized(ServiceInfoV2.class, Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile Object name_ = "";
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return The name.
*/
@Override
public String getName() {
Object ref = name_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return The bytes for name.
*/
@Override
public com.google.protobuf.ByteString getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GROUP_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile Object group_ = "";
/**
* <pre>
* The service group.
* </pre>
*
* <code>string group = 2;</code>
* @return The group.
*/
@Override
public String getGroup() {
Object ref = group_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
group_ = s;
return s;
}
}
/**
* <pre>
* The service group.
* </pre>
*
* <code>string group = 2;</code>
* @return The bytes for group.
*/
@Override
public com.google.protobuf.ByteString getGroupBytes() {
Object ref = group_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
group_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile Object version_ = "";
/**
* <pre>
* The service version.
* </pre>
*
* <code>string version = 3;</code>
* @return The version.
*/
@Override
public String getVersion() {
Object ref = version_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
version_ = s;
return s;
}
}
/**
* <pre>
* The service version.
* </pre>
*
* <code>string version = 3;</code>
* @return The bytes for version.
*/
@Override
public com.google.protobuf.ByteString getVersionBytes() {
Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROTOCOL_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile Object protocol_ = "";
/**
* <pre>
* The service protocol.
* </pre>
*
* <code>string protocol = 4;</code>
* @return The protocol.
*/
@Override
public String getProtocol() {
Object ref = protocol_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
protocol_ = s;
return s;
}
}
/**
* <pre>
* The service protocol.
* </pre>
*
* <code>string protocol = 4;</code>
* @return The bytes for protocol.
*/
@Override
public com.google.protobuf.ByteString getProtocolBytes() {
Object ref = protocol_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
protocol_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PORT_FIELD_NUMBER = 5;
private int port_ = 0;
/**
* <pre>
* The service port.
* </pre>
*
* <code>int32 port = 5;</code>
* @return The port.
*/
@Override
public int getPort() {
return port_;
}
public static final int PATH_FIELD_NUMBER = 6;
@SuppressWarnings("serial")
private volatile Object path_ = "";
/**
* <pre>
* The service path.
* </pre>
*
* <code>string path = 6;</code>
* @return The path.
*/
@Override
public String getPath() {
Object ref = path_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
path_ = s;
return s;
}
}
/**
* <pre>
* The service path.
* </pre>
*
* <code>string path = 6;</code>
* @return The bytes for path.
*/
@Override
public com.google.protobuf.ByteString getPathBytes() {
Object ref = path_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
path_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PARAMS_FIELD_NUMBER = 7;
private static final class ParamsDefaultEntryHolder {
static final com.google.protobuf.MapEntry<String, String> defaultEntry =
com.google.protobuf.MapEntry.<String, String>newDefaultInstance(
MetadataServiceV2OuterClass
.internal_static_org_apache_dubbo_metadata_ServiceInfoV2_ParamsEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.STRING,
"");
}
@SuppressWarnings("serial")
private com.google.protobuf.MapField<String, String> params_;
private com.google.protobuf.MapField<String, String> internalGetParams() {
if (params_ == null) {
return com.google.protobuf.MapField.emptyMapField(ParamsDefaultEntryHolder.defaultEntry);
}
return params_;
}
public int getParamsCount() {
return internalGetParams().getMap().size();
}
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
@Override
public boolean containsParams(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetParams().getMap().containsKey(key);
}
/**
* Use {@link #getParamsMap()} instead.
*/
@Override
@Deprecated
public java.util.Map<String, String> getParams() {
return getParamsMap();
}
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
@Override
public java.util.Map<String, String> getParamsMap() {
return internalGetParams().getMap();
}
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
@Override
public /* nullable */ String getParamsOrDefault(
String key,
/* nullable */
String defaultValue) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<String, String> map = internalGetParams().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
@Override
public String getParamsOrThrow(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<String, String> map = internalGetParams().getMap();
if (!map.containsKey(key)) {
throw new IllegalArgumentException();
}
return map.get(key);
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(group_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, group_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, version_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(protocol_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, protocol_);
}
if (port_ != 0) {
output.writeInt32(5, port_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(path_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, path_);
}
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetParams(), ParamsDefaultEntryHolder.defaultEntry, 7);
getUnknownFields().writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(group_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, group_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, version_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(protocol_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, protocol_);
}
if (port_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(5, port_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(path_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, path_);
}
for (java.util.Map.Entry<String, String> entry :
internalGetParams().getMap().entrySet()) {
com.google.protobuf.MapEntry<String, String> params__ = ParamsDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(7, params__);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ServiceInfoV2)) {
return super.equals(obj);
}
ServiceInfoV2 other = (ServiceInfoV2) obj;
if (!getName().equals(other.getName())) {
return false;
}
if (!getGroup().equals(other.getGroup())) {
return false;
}
if (!getVersion().equals(other.getVersion())) {
return false;
}
if (!getProtocol().equals(other.getProtocol())) {
return false;
}
if (getPort() != other.getPort()) {
return false;
}
if (!getPath().equals(other.getPath())) {
return false;
}
if (!internalGetParams().equals(other.internalGetParams())) {
return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + GROUP_FIELD_NUMBER;
hash = (53 * hash) + getGroup().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
hash = (37 * hash) + PROTOCOL_FIELD_NUMBER;
hash = (53 * hash) + getProtocol().hashCode();
hash = (37 * hash) + PORT_FIELD_NUMBER;
hash = (53 * hash) + getPort();
hash = (37 * hash) + PATH_FIELD_NUMBER;
hash = (53 * hash) + getPath().hashCode();
if (!internalGetParams().getMap().isEmpty()) {
hash = (37 * hash) + PARAMS_FIELD_NUMBER;
hash = (53 * hash) + internalGetParams().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static ServiceInfoV2 parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ServiceInfoV2 parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ServiceInfoV2 parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ServiceInfoV2 parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ServiceInfoV2 parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static ServiceInfoV2 parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static ServiceInfoV2 parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static ServiceInfoV2 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 ServiceInfoV2 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static ServiceInfoV2 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 ServiceInfoV2 parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static ServiceInfoV2 parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(ServiceInfoV2 prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Service information message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.ServiceInfoV2}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.ServiceInfoV2)
ServiceInfoV2OrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 7:
return internalGetParams();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMutableMapField(int number) {
switch (number) {
case 7:
return internalGetMutableParams();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass
.internal_static_org_apache_dubbo_metadata_ServiceInfoV2_fieldAccessorTable
.ensureFieldAccessorsInitialized(ServiceInfoV2.class, Builder.class);
}
// Construct using org.apache.dubbo.metadata.ServiceInfoV2.newBuilder()
private Builder() {}
private Builder(BuilderParent parent) {
super(parent);
}
@Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
group_ = "";
version_ = "";
protocol_ = "";
port_ = 0;
path_ = "";
internalGetMutableParams().clear();
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor;
}
@Override
public ServiceInfoV2 getDefaultInstanceForType() {
return ServiceInfoV2.getDefaultInstance();
}
@Override
public ServiceInfoV2 build() {
ServiceInfoV2 result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public ServiceInfoV2 buildPartial() {
ServiceInfoV2 result = new ServiceInfoV2(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(ServiceInfoV2 result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.group_ = group_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.version_ = version_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.protocol_ = protocol_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.port_ = port_;
}
if (((from_bitField0_ & 0x00000020) != 0)) {
result.path_ = path_;
}
if (((from_bitField0_ & 0x00000040) != 0)) {
result.params_ = internalGetParams();
result.params_.makeImmutable();
}
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof ServiceInfoV2) {
return mergeFrom((ServiceInfoV2) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(ServiceInfoV2 other) {
if (other == ServiceInfoV2.getDefaultInstance()) {
return this;
}
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getGroup().isEmpty()) {
group_ = other.group_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getProtocol().isEmpty()) {
protocol_ = other.protocol_;
bitField0_ |= 0x00000008;
onChanged();
}
if (other.getPort() != 0) {
setPort(other.getPort());
}
if (!other.getPath().isEmpty()) {
path_ = other.path_;
bitField0_ |= 0x00000020;
onChanged();
}
internalGetMutableParams().mergeFrom(other.internalGetParams());
bitField0_ |= 0x00000040;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
group_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26: {
version_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34: {
protocol_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 40: {
port_ = input.readInt32();
bitField0_ |= 0x00000010;
break;
} // case 40
case 50: {
path_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000020;
break;
} // case 50
case 58: {
com.google.protobuf.MapEntry<String, String> params__ = input.readMessage(
ParamsDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry);
internalGetMutableParams().getMutableMap().put(params__.getKey(), params__.getValue());
bitField0_ |= 0x00000040;
break;
} // case 58
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private Object name_ = "";
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return The name.
*/
public String getName() {
Object ref = name_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingChangedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import java.util.Set;
public class MappingChangedEvent {
private final String serviceKey;
private final Set<String> apps;
public MappingChangedEvent(String serviceKey, Set<String> apps) {
this.serviceKey = serviceKey;
this.apps = apps;
}
public String getServiceKey() {
return serviceKey;
}
public Set<String> getApps() {
return apps;
}
@Override
public String toString() {
return "{serviceKey: " + serviceKey + ", apps: " + apps.toString() + "}";
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/RevisionResolver.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.utils.MD5Utils;
public class RevisionResolver {
public static final String EMPTY_REVISION = "0";
private static MD5Utils md5Utils = new MD5Utils();
public static String calRevision(String metadata) {
return md5Utils.getMd5(metadata);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfoV2OrBuilder.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfoV2OrBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface MetadataInfoV2OrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.MetadataInfoV2)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return The app.
*/
String getApp();
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return The bytes for app.
*/
com.google.protobuf.ByteString getAppBytes();
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return The version.
*/
String getVersion();
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return The bytes for version.
*/
com.google.protobuf.ByteString getVersionBytes();
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
int getServicesCount();
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
boolean containsServices(String key);
/**
* Use {@link #getServicesMap()} instead.
*/
@Deprecated
java.util.Map<String, ServiceInfoV2> getServices();
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
java.util.Map<String, ServiceInfoV2> getServicesMap();
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
/* nullable */
ServiceInfoV2 getServicesOrDefault(
String key,
/* nullable */
ServiceInfoV2 defaultValue);
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
ServiceInfoV2 getServicesOrThrow(String key);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceV2OuterClass.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceV2OuterClass.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public final class MetadataServiceV2OuterClass {
private MetadataServiceV2OuterClass() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_MetadataRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_MetadataRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_ParamsEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_ParamsEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_OpenAPIRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_OpenAPIRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_org_apache_dubbo_metadata_OpenAPIInfo_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_org_apache_dubbo_metadata_OpenAPIInfo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
String[] descriptorData = {
"\n\031metadata_service_v2.proto\022\031org.apache."
+ "dubbo.metadata\"#\n\017MetadataRequest\022\020\n\010rev"
+ "ision\030\001 \001(\t\"\324\001\n\016MetadataInfoV2\022\013\n\003app\030\001 "
+ "\001(\t\022\017\n\007version\030\002 \001(\t\022I\n\010services\030\003 \003(\01327"
+ ".org.apache.dubbo.metadata.MetadataInfoV"
+ "2.ServicesEntry\032Y\n\rServicesEntry\022\013\n\003key\030"
+ "\001 \001(\t\0227\n\005value\030\002 \001(\0132(.org.apache.dubbo."
+ "metadata.ServiceInfoV2:\0028\001\"\340\001\n\rServiceIn"
+ "foV2\022\014\n\004name\030\001 \001(\t\022\r\n\005group\030\002 \001(\t\022\017\n\007ver"
+ "sion\030\003 \001(\t\022\020\n\010protocol\030\004 \001(\t\022\014\n\004port\030\005 \001"
+ "(\005\022\014\n\004path\030\006 \001(\t\022D\n\006params\030\007 \003(\01324.org.a"
+ "pache.dubbo.metadata.ServiceInfoV2.Param"
+ "sEntry\032-\n\013ParamsEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005va"
+ "lue\030\002 \001(\t:\0028\001\"\311\001\n\016OpenAPIRequest\022\r\n\005grou"
+ "p\030\001 \001(\t\022\017\n\007version\030\002 \001(\t\022\013\n\003tag\030\003 \003(\t\022\017\n"
+ "\007service\030\004 \003(\t\022\017\n\007openapi\030\005 \001(\t\022=\n\006forma"
+ "t\030\006 \001(\0162(.org.apache.dubbo.metadata.Open"
+ "APIFormatH\000\210\001\001\022\023\n\006pretty\030\007 \001(\010H\001\210\001\001B\t\n\007_"
+ "formatB\t\n\007_pretty\"!\n\013OpenAPIInfo\022\022\n\ndefi"
+ "nition\030\001 \001(\t*.\n\rOpenAPIFormat\022\010\n\004JSON\020\000\022"
+ "\010\n\004YAML\020\001\022\t\n\005PROTO\020\0022\342\001\n\021MetadataService"
+ "V2\022h\n\017GetMetadataInfo\022*.org.apache.dubbo"
+ ".metadata.MetadataRequest\032).org.apache.d"
+ "ubbo.metadata.MetadataInfoV2\022c\n\016GetOpenA"
+ "PIInfo\022).org.apache.dubbo.metadata.OpenA"
+ "PIRequest\032&.org.apache.dubbo.metadata.Op"
+ "enAPIInfoBZ\n\031org.apache.dubbo.metadataP\001"
+ "Z;dubbo.apache.org/dubbo-go/v3/metadata/"
+ "triple_api;triple_apib\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {});
internal_static_org_apache_dubbo_metadata_MetadataRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_org_apache_dubbo_metadata_MetadataRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_MetadataRequest_descriptor, new String[] {
"Revision",
});
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor, new String[] {
"App", "Version", "Services",
});
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_descriptor =
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor
.getNestedTypes()
.get(0);
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_descriptor,
new String[] {
"Key", "Value",
});
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor, new String[] {
"Name", "Group", "Version", "Protocol", "Port", "Path", "Params",
});
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_ParamsEntry_descriptor =
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_descriptor
.getNestedTypes()
.get(0);
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_ParamsEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_ServiceInfoV2_ParamsEntry_descriptor, new String[] {
"Key", "Value",
});
internal_static_org_apache_dubbo_metadata_OpenAPIRequest_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_org_apache_dubbo_metadata_OpenAPIRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_OpenAPIRequest_descriptor, new String[] {
"Group", "Version", "Tag", "Service", "Openapi", "Format", "Pretty", "Format", "Pretty",
});
internal_static_org_apache_dubbo_metadata_OpenAPIInfo_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_org_apache_dubbo_metadata_OpenAPIInfo_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_org_apache_dubbo_metadata_OpenAPIInfo_descriptor, new String[] {
"Definition",
});
}
// @@protoc_insertion_point(outer_class_scope)
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataRequestOrBuilder.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataRequestOrBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface MetadataRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.MetadataRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return The revision.
*/
String getRevision();
/**
* <pre>
* The revision of the metadata.
* </pre>
*
* <code>string revision = 1;</code>
* @return The bytes for revision.
*/
com.google.protobuf.ByteString getRevisionBytes();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataParamsFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.extension.SPI;
/**
* This filter applies an either 'include' or 'exclude' policy with 'include' having higher priority.
* That means if 'include' is specified then params specified in 'exclude' will be ignored
*
* If multiple Filter extensions are provided, then,
* 1. All params specified as should be included within different Filter extension instances will determine the params that will finally be used.
* 2. If none of the Filter extensions specified any params as should be included, then the final effective params would be those left after removed all the params specified as should be excluded.
*
* It is recommended for most users to use 'exclude' policy for service params and 'include' policy for instance params.
* Please use 'params-filter=-default, -filterName1, filterName2' to activate or deactivate filter extensions.
*/
@SPI
public interface MetadataParamsFilter {
/**
* params that need to be sent to metadata center
*
* @return arrays of keys
*/
default String[] serviceParamsIncluded() {
return new String[0];
}
/**
* params that need to be excluded before sending to metadata center
*
* @return arrays of keys
*/
default String[] serviceParamsExcluded() {
return new String[0];
}
/**
* params that need to be sent to registry center
*
* @return arrays of keys
*/
default String[] instanceParamsIncluded() {
return new String[0];
}
/**
* params that need to be excluded before sending to registry center
*
* @return arrays of keys
*/
default String[] instanceParamsExcluded() {
return new String[0];
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIInfo.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIInfo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* <pre>
* OpenAPI information message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.OpenAPIInfo}
*/
public final class OpenAPIInfo extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.OpenAPIInfo)
OpenAPIInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use OpenAPIInfo.newBuilder() to construct.
private OpenAPIInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private OpenAPIInfo() {
definition_ = "";
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new OpenAPIInfo();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIInfo_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(OpenAPIInfo.class, Builder.class);
}
public static final int DEFINITION_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile Object definition_ = "";
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return The definition.
*/
@Override
public String getDefinition() {
Object ref = definition_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
definition_ = s;
return s;
}
}
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return The bytes for definition.
*/
@Override
public com.google.protobuf.ByteString getDefinitionBytes() {
Object ref = definition_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
definition_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(definition_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, definition_);
}
getUnknownFields().writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(definition_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, definition_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof OpenAPIInfo)) {
return super.equals(obj);
}
OpenAPIInfo other = (OpenAPIInfo) obj;
if (!getDefinition().equals(other.getDefinition())) {
return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + DEFINITION_FIELD_NUMBER;
hash = (53 * hash) + getDefinition().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static OpenAPIInfo parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static OpenAPIInfo parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static OpenAPIInfo parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static OpenAPIInfo parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static OpenAPIInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static OpenAPIInfo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static OpenAPIInfo parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static OpenAPIInfo 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 OpenAPIInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static OpenAPIInfo 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 OpenAPIInfo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static OpenAPIInfo parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(OpenAPIInfo prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* OpenAPI information message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.OpenAPIInfo}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.OpenAPIInfo)
OpenAPIInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIInfo_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(OpenAPIInfo.class, Builder.class);
}
// Construct using org.apache.dubbo.metadata.OpenAPIInfo.newBuilder()
private Builder() {}
private Builder(BuilderParent parent) {
super(parent);
}
@Override
public Builder clear() {
super.clear();
bitField0_ = 0;
definition_ = "";
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIInfo_descriptor;
}
@Override
public OpenAPIInfo getDefaultInstanceForType() {
return OpenAPIInfo.getDefaultInstance();
}
@Override
public OpenAPIInfo build() {
OpenAPIInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public OpenAPIInfo buildPartial() {
OpenAPIInfo result = new OpenAPIInfo(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(OpenAPIInfo result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.definition_ = definition_;
}
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof OpenAPIInfo) {
return mergeFrom((OpenAPIInfo) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(OpenAPIInfo other) {
if (other == OpenAPIInfo.getDefaultInstance()) {
return this;
}
if (!other.getDefinition().isEmpty()) {
definition_ = other.definition_;
bitField0_ |= 0x00000001;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
definition_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private Object definition_ = "";
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return The definition.
*/
public String getDefinition() {
Object ref = definition_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
definition_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return The bytes for definition.
*/
public com.google.protobuf.ByteString getDefinitionBytes() {
Object ref = definition_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
definition_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @param value The definition to set.
* @return This builder for chaining.
*/
public Builder setDefinition(String value) {
if (value == null) {
throw new NullPointerException();
}
definition_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @return This builder for chaining.
*/
public Builder clearDefinition() {
definition_ = getDefaultInstance().getDefinition();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* The OpenAPI definition.
* </pre>
*
* <code>string definition = 1;</code>
* @param value The bytes for definition to set.
* @return This builder for chaining.
*/
public Builder setDefinitionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
definition_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
@Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@Override
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:org.apache.dubbo.metadata.OpenAPIInfo)
}
// @@protoc_insertion_point(class_scope:org.apache.dubbo.metadata.OpenAPIInfo)
private static final OpenAPIInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new OpenAPIInfo();
}
public static OpenAPIInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<OpenAPIInfo> PARSER =
new com.google.protobuf.AbstractParser<OpenAPIInfo>() {
@Override
public OpenAPIInfo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<OpenAPIInfo> parser() {
return PARSER;
}
@Override
public com.google.protobuf.Parser<OpenAPIInfo> getParserForType() {
return PARSER;
}
@Override
public OpenAPIInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractServiceNameMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableSet;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.of;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_LOAD_MAPPING_CACHE;
import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.toTreeSet;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
public abstract class AbstractServiceNameMapping implements ServiceNameMapping {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
protected ApplicationModel applicationModel;
private final MappingCacheManager mappingCacheManager;
private final ConcurrentHashMap<String, Set<MappingListener>> mappingListeners = new ConcurrentHashMap<>();
// mapping lock is shared among registries of the same application.
private final ConcurrentMap<String, ReentrantLock> mappingLocks = new ConcurrentHashMap<>();
public AbstractServiceNameMapping(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
boolean enableFileCache = true;
Optional<ApplicationConfig> application =
applicationModel.getApplicationConfigManager().getApplication();
if (application.isPresent()) {
enableFileCache = Boolean.TRUE.equals(application.get().getEnableFileCache()) ? true : false;
}
this.mappingCacheManager = new MappingCacheManager(
enableFileCache,
applicationModel.tryGetApplicationName(),
applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getCacheRefreshingScheduledExecutor());
}
// just for test
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
/**
* Get the service names from the specified Dubbo service interface, group, version and protocol
*
* @return
*/
public abstract Set<String> get(URL url);
/**
* Get the service names from the specified Dubbo service interface, group, version and protocol
*
* @return
*/
public abstract Set<String> getAndListen(URL url, MappingListener mappingListener);
protected abstract void removeListener(URL url, MappingListener mappingListener);
@Override
public Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) {
String key = ServiceNameMapping.buildMappingKey(subscribedURL);
// use previously cached services.
Set<String> mappingServices = mappingCacheManager.get(key);
// Asynchronously register listener in case previous cache does not exist or cache expired.
if (CollectionUtils.isEmpty(mappingServices)) {
try {
logger.info("[METADATA_REGISTER] Local cache mapping is empty");
mappingServices = (new AsyncMappingTask(listener, subscribedURL, false)).call();
} catch (Exception e) {
// ignore
}
if (CollectionUtils.isEmpty(mappingServices)) {
String registryServices = registryURL.getParameter(SUBSCRIBED_SERVICE_NAMES_KEY);
if (StringUtils.isNotEmpty(registryServices)) {
logger.info(subscribedURL.getServiceInterface() + " mapping to " + registryServices
+ " instructed by registry subscribed-services.");
mappingServices = parseServices(registryServices);
}
}
if (CollectionUtils.isNotEmpty(mappingServices)) {
this.putCachedMapping(ServiceNameMapping.buildMappingKey(subscribedURL), mappingServices);
}
} else {
ExecutorService executorService = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getMappingRefreshingExecutor();
executorService.submit(new AsyncMappingTask(listener, subscribedURL, true));
}
return mappingServices;
}
@Override
public MappingListener stopListen(URL subscribeURL, MappingListener listener) {
synchronized (mappingListeners) {
if (listener != null) {
String mappingKey = ServiceNameMapping.buildMappingKey(subscribeURL);
Set<MappingListener> listeners = mappingListeners.get(mappingKey);
// todo, remove listener from remote metadata center
if (CollectionUtils.isNotEmpty(listeners)) {
listeners.remove(listener);
listener.stop();
removeListener(subscribeURL, listener);
}
if (CollectionUtils.isEmpty(listeners)) {
mappingListeners.remove(mappingKey);
removeCachedMapping(mappingKey);
removeMappingLock(mappingKey);
}
}
return listener;
}
}
static Set<String> parseServices(String literalServices) {
return isBlank(literalServices)
? emptySet()
: unmodifiableSet(new TreeSet<>(of(literalServices.split(","))
.map(String::trim)
.filter(StringUtils::isNotEmpty)
.collect(toSet())));
}
@Override
public void putCachedMapping(String serviceKey, Set<String> apps) {
mappingCacheManager.put(serviceKey, toTreeSet(apps));
}
protected void putCachedMappingIfAbsent(String serviceKey, Set<String> apps) {
Lock lock = getMappingLock(serviceKey);
try {
lock.lock();
if (CollectionUtils.isEmpty(mappingCacheManager.get(serviceKey))) {
mappingCacheManager.put(serviceKey, toTreeSet(apps));
}
} finally {
lock.unlock();
}
}
@Override
public Set<String> getMapping(URL consumerURL) {
Set<String> mappingByUrl = ServiceNameMapping.getMappingByUrl(consumerURL);
if (mappingByUrl != null) {
return mappingByUrl;
}
return mappingCacheManager.get(ServiceNameMapping.buildMappingKey(consumerURL));
}
@Override
public Set<String> getRemoteMapping(URL consumerURL) {
return get(consumerURL);
}
@Override
public Set<String> removeCachedMapping(String serviceKey) {
return mappingCacheManager.remove(serviceKey);
}
public Lock getMappingLock(String key) {
return ConcurrentHashMapUtils.computeIfAbsent(mappingLocks, key, _k -> new ReentrantLock());
}
protected void removeMappingLock(String key) {
Lock lock = mappingLocks.get(key);
if (lock != null) {
try {
lock.lock();
mappingLocks.remove(key);
} finally {
lock.unlock();
}
}
}
@Override
public void $destroy() {
mappingCacheManager.destroy();
mappingListeners.clear();
mappingLocks.clear();
}
private class AsyncMappingTask implements Callable<Set<String>> {
private final MappingListener listener;
private final URL subscribedURL;
private final boolean notifyAtFirstTime;
public AsyncMappingTask(MappingListener listener, URL subscribedURL, boolean notifyAtFirstTime) {
this.listener = listener;
this.subscribedURL = subscribedURL;
this.notifyAtFirstTime = notifyAtFirstTime;
}
@Override
public Set<String> call() throws Exception {
synchronized (mappingListeners) {
Set<String> mappedServices = emptySet();
try {
String mappingKey = ServiceNameMapping.buildMappingKey(subscribedURL);
if (listener != null) {
mappedServices = toTreeSet(getAndListen(subscribedURL, listener));
Set<MappingListener> listeners = ConcurrentHashMapUtils.computeIfAbsent(
mappingListeners, mappingKey, _k -> new HashSet<>());
listeners.add(listener);
if (CollectionUtils.isNotEmpty(mappedServices)) {
if (notifyAtFirstTime) {
// guarantee at-least-once notification no matter what kind of underlying meta server is
// used.
// listener notification will also cause updating of mapping cache.
listener.onEvent(new MappingChangedEvent(mappingKey, mappedServices));
}
}
} else {
mappedServices = get(subscribedURL);
if (CollectionUtils.isNotEmpty(mappedServices)) {
AbstractServiceNameMapping.this.putCachedMapping(mappingKey, mappedServices);
}
}
} catch (Exception e) {
logger.error(
COMMON_FAILED_LOAD_MAPPING_CACHE,
"",
"",
"Failed getting mapping info from remote center. ",
e);
}
return mappedServices;
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DefaultMetadataParamsFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.extension.Activate;
import static org.apache.dubbo.common.constants.CommonConstants.IPV6_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.apache.dubbo.remoting.Constants.HEARTBEAT_TIMEOUT_KEY;
import static org.apache.dubbo.rpc.Constants.INTERFACES;
@Activate
public class DefaultMetadataParamsFilter implements MetadataParamsFilter {
private final String[] excludedServiceParams;
private final String[] includedInstanceParams;
public DefaultMetadataParamsFilter() {
this.includedInstanceParams = new String[] {HEARTBEAT_TIMEOUT_KEY, TIMESTAMP_KEY, IPV6_KEY};
this.excludedServiceParams = new String[] {
MONITOR_KEY,
BIND_IP_KEY,
BIND_PORT_KEY,
QOS_ENABLE,
QOS_HOST,
QOS_PORT,
ACCEPT_FOREIGN_IP,
VALIDATION_KEY,
INTERFACES,
PID_KEY,
TIMESTAMP_KEY,
HEARTBEAT_TIMEOUT_KEY,
IPV6_KEY
};
}
@Override
public String[] instanceParamsIncluded() {
return includedInstanceParams;
}
@Override
public String[] serviceParamsExcluded() {
return excludedServiceParams;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/AbstractCacheManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.cache.FileCacheStore;
import org.apache.dubbo.common.cache.FileCacheStoreFactory;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.LRUCache;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_LOAD_MAPPING_CACHE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
public abstract class AbstractCacheManager<V> implements Disposable {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private ScheduledExecutorService executorService;
protected FileCacheStore cacheStore;
protected LRUCache<String, V> cache;
protected void init(
boolean enableFileCache,
String filePath,
String fileName,
int entrySize,
long fileSize,
int interval,
ScheduledExecutorService executorService) {
this.cache = new LRUCache<>(entrySize);
try {
cacheStore = FileCacheStoreFactory.getInstance(filePath, fileName, enableFileCache);
Map<String, String> properties = cacheStore.loadCache(entrySize);
if (logger.isDebugEnabled()) {
logger.debug("Successfully loaded " + getName() + " cache from file " + fileName + ", entries "
+ properties.size());
}
for (Map.Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
V v = toValueType(value);
put(key, v);
}
// executorService can be empty if FileCacheStore fails
if (executorService == null) {
this.executorService = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("Dubbo-cache-refreshing-scheduler", true));
} else {
this.executorService = executorService;
}
this.executorService.scheduleWithFixedDelay(
new CacheRefreshTask<>(this.cacheStore, this.cache, this, fileSize),
10,
interval,
TimeUnit.MINUTES);
} catch (Exception e) {
logger.error(COMMON_FAILED_LOAD_MAPPING_CACHE, "", "", "Load mapping from local cache file error ", e);
}
}
protected abstract V toValueType(String value);
protected abstract String getName();
protected boolean validate(String key, V value) {
return value != null;
}
public V get(String key) {
return cache.get(key);
}
public void put(String key, V apps) {
if (validate(key, apps)) {
cache.put(key, apps);
}
}
public V remove(String key) {
return cache.remove(key);
}
public Map<String, V> getAll() {
if (cache.isEmpty()) {
return Collections.emptyMap();
}
Map<String, V> copyMap = new HashMap<>();
cache.lock();
try {
for (Map.Entry<String, V> entry : cache.entrySet()) {
copyMap.put(entry.getKey(), entry.getValue());
}
} finally {
cache.releaseLock();
}
return Collections.unmodifiableMap(copyMap);
}
public void update(Map<String, V> newCache) {
for (Map.Entry<String, V> entry : newCache.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public void destroy() {
if (executorService != null) {
executorService.shutdownNow();
try {
if (!executorService.awaitTermination(
ConfigurationUtils.reCalShutdownTime(DEFAULT_SERVER_SHUTDOWN_TIMEOUT), TimeUnit.MILLISECONDS)) {
logger.warn(
COMMON_UNEXPECTED_EXCEPTION, "", "", "Wait global executor service terminated timeout.");
}
} catch (InterruptedException e) {
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "destroy resources failed: " + e.getMessage(), e);
}
}
if (cacheStore != null) {
cacheStore.destroy();
}
if (cache != null) {
cache.clear();
}
}
public static class CacheRefreshTask<V> implements Runnable {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private static final String DEFAULT_COMMENT = "Dubbo cache";
private final FileCacheStore cacheStore;
private final LRUCache<String, V> cache;
private final AbstractCacheManager<V> cacheManager;
private final long maxFileSize;
public CacheRefreshTask(
FileCacheStore cacheStore,
LRUCache<String, V> cache,
AbstractCacheManager<V> cacheManager,
long maxFileSize) {
this.cacheStore = cacheStore;
this.cache = cache;
this.cacheManager = cacheManager;
this.maxFileSize = maxFileSize;
}
@Override
public void run() {
Map<String, String> properties = new HashMap<>();
cache.lock();
try {
for (Map.Entry<String, V> entry : cache.entrySet()) {
properties.put(entry.getKey(), JsonUtils.toJson(entry.getValue()));
}
} finally {
cache.releaseLock();
}
if (logger.isDebugEnabled()) {
logger.debug("Dumping " + cacheManager.getName() + " caches, latest entries " + properties.size());
}
cacheStore.refreshCache(properties, DEFAULT_COMMENT, maxFileSize);
}
}
// for test unit
public FileCacheStore getCacheStore() {
return cacheStore;
}
public LRUCache<String, V> getCache() {
return cache;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfoV2.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfoV2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* <pre>
* Metadata information message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.MetadataInfoV2}
*/
public final class MetadataInfoV2 extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.MetadataInfoV2)
MetadataInfoV2OrBuilder {
private static final long serialVersionUID = 0L;
// Use MetadataInfoV2.newBuilder() to construct.
private MetadataInfoV2(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MetadataInfoV2() {
app_ = "";
version_ = "";
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new MetadataInfoV2();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor;
}
@SuppressWarnings({"rawtypes"})
@Override
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 3:
return internalGetServices();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_fieldAccessorTable
.ensureFieldAccessorsInitialized(MetadataInfoV2.class, Builder.class);
}
public static final int APP_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile Object app_ = "";
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return The app.
*/
@Override
public String getApp() {
Object ref = app_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
app_ = s;
return s;
}
}
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return The bytes for app.
*/
@Override
public com.google.protobuf.ByteString getAppBytes() {
Object ref = app_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
app_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile Object version_ = "";
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return The version.
*/
@Override
public String getVersion() {
Object ref = version_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
version_ = s;
return s;
}
}
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return The bytes for version.
*/
@Override
public com.google.protobuf.ByteString getVersionBytes() {
Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SERVICES_FIELD_NUMBER = 3;
private static final class ServicesDefaultEntryHolder {
static final com.google.protobuf.MapEntry<String, ServiceInfoV2> defaultEntry =
com.google.protobuf.MapEntry.<String, ServiceInfoV2>newDefaultInstance(
MetadataServiceV2OuterClass
.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_ServicesEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.MESSAGE,
ServiceInfoV2.getDefaultInstance());
}
@SuppressWarnings("serial")
private com.google.protobuf.MapField<String, ServiceInfoV2> services_;
private com.google.protobuf.MapField<String, ServiceInfoV2> internalGetServices() {
if (services_ == null) {
return com.google.protobuf.MapField.emptyMapField(ServicesDefaultEntryHolder.defaultEntry);
}
return services_;
}
public int getServicesCount() {
return internalGetServices().getMap().size();
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public boolean containsServices(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetServices().getMap().containsKey(key);
}
/**
* Use {@link #getServicesMap()} instead.
*/
@Override
@Deprecated
public java.util.Map<String, ServiceInfoV2> getServices() {
return getServicesMap();
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public java.util.Map<String, ServiceInfoV2> getServicesMap() {
return internalGetServices().getMap();
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public /* nullable */ ServiceInfoV2 getServicesOrDefault(
String key,
/* nullable */
ServiceInfoV2 defaultValue) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public ServiceInfoV2 getServicesOrThrow(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap();
if (!map.containsKey(key)) {
throw new IllegalArgumentException();
}
return map.get(key);
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(app_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, app_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, version_);
}
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetServices(), ServicesDefaultEntryHolder.defaultEntry, 3);
getUnknownFields().writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(app_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, app_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, version_);
}
for (java.util.Map.Entry<String, ServiceInfoV2> entry :
internalGetServices().getMap().entrySet()) {
com.google.protobuf.MapEntry<String, ServiceInfoV2> services__ = ServicesDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, services__);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MetadataInfoV2)) {
return super.equals(obj);
}
MetadataInfoV2 other = (MetadataInfoV2) obj;
if (!getApp().equals(other.getApp())) {
return false;
}
if (!getVersion().equals(other.getVersion())) {
return false;
}
if (!internalGetServices().equals(other.internalGetServices())) {
return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + APP_FIELD_NUMBER;
hash = (53 * hash) + getApp().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
if (!internalGetServices().getMap().isEmpty()) {
hash = (37 * hash) + SERVICES_FIELD_NUMBER;
hash = (53 * hash) + internalGetServices().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static MetadataInfoV2 parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static MetadataInfoV2 parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static MetadataInfoV2 parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static MetadataInfoV2 parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static MetadataInfoV2 parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static MetadataInfoV2 parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static MetadataInfoV2 parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static MetadataInfoV2 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 MetadataInfoV2 parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static MetadataInfoV2 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 MetadataInfoV2 parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static MetadataInfoV2 parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(MetadataInfoV2 prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Metadata information message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.MetadataInfoV2}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.MetadataInfoV2)
MetadataInfoV2OrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 3:
return internalGetServices();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMutableMapField(int number) {
switch (number) {
case 3:
return internalGetMutableServices();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass
.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_fieldAccessorTable
.ensureFieldAccessorsInitialized(MetadataInfoV2.class, Builder.class);
}
// Construct using org.apache.dubbo.metadata.MetadataInfoV2.newBuilder()
private Builder() {}
private Builder(BuilderParent parent) {
super(parent);
}
@Override
public Builder clear() {
super.clear();
bitField0_ = 0;
app_ = "";
version_ = "";
internalGetMutableServices().clear();
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_MetadataInfoV2_descriptor;
}
@Override
public MetadataInfoV2 getDefaultInstanceForType() {
return MetadataInfoV2.getDefaultInstance();
}
@Override
public MetadataInfoV2 build() {
MetadataInfoV2 result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public MetadataInfoV2 buildPartial() {
MetadataInfoV2 result = new MetadataInfoV2(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(MetadataInfoV2 result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.app_ = app_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.version_ = version_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.services_ = internalGetServices();
result.services_.makeImmutable();
}
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof MetadataInfoV2) {
return mergeFrom((MetadataInfoV2) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(MetadataInfoV2 other) {
if (other == MetadataInfoV2.getDefaultInstance()) {
return this;
}
if (!other.getApp().isEmpty()) {
app_ = other.app_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
bitField0_ |= 0x00000002;
onChanged();
}
internalGetMutableServices().mergeFrom(other.internalGetServices());
bitField0_ |= 0x00000004;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
app_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
version_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26: {
com.google.protobuf.MapEntry<String, ServiceInfoV2> services__ = input.readMessage(
ServicesDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry);
internalGetMutableServices()
.getMutableMap()
.put(services__.getKey(), services__.getValue());
bitField0_ |= 0x00000004;
break;
} // case 26
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private Object app_ = "";
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return The app.
*/
public String getApp() {
Object ref = app_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
app_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return The bytes for app.
*/
public com.google.protobuf.ByteString getAppBytes() {
Object ref = app_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
app_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @param value The app to set.
* @return This builder for chaining.
*/
public Builder setApp(String value) {
if (value == null) {
throw new NullPointerException();
}
app_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @return This builder for chaining.
*/
public Builder clearApp() {
app_ = getDefaultInstance().getApp();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* The application name.
* </pre>
*
* <code>string app = 1;</code>
* @param value The bytes for app to set.
* @return This builder for chaining.
*/
public Builder setAppBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
app_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private Object version_ = "";
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return The version.
*/
public String getVersion() {
Object ref = version_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
version_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return The bytes for version.
*/
public com.google.protobuf.ByteString getVersionBytes() {
Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @param value The version to set.
* @return This builder for chaining.
*/
public Builder setVersion(String value) {
if (value == null) {
throw new NullPointerException();
}
version_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @return This builder for chaining.
*/
public Builder clearVersion() {
version_ = getDefaultInstance().getVersion();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* The application version.
* </pre>
*
* <code>string version = 2;</code>
* @param value The bytes for version to set.
* @return This builder for chaining.
*/
public Builder setVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
version_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.MapField<String, ServiceInfoV2> services_;
private com.google.protobuf.MapField<String, ServiceInfoV2> internalGetServices() {
if (services_ == null) {
return com.google.protobuf.MapField.emptyMapField(ServicesDefaultEntryHolder.defaultEntry);
}
return services_;
}
private com.google.protobuf.MapField<String, ServiceInfoV2> internalGetMutableServices() {
if (services_ == null) {
services_ = com.google.protobuf.MapField.newMapField(ServicesDefaultEntryHolder.defaultEntry);
}
if (!services_.isMutable()) {
services_ = services_.copy();
}
bitField0_ |= 0x00000004;
onChanged();
return services_;
}
public int getServicesCount() {
return internalGetServices().getMap().size();
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public boolean containsServices(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetServices().getMap().containsKey(key);
}
/**
* Use {@link #getServicesMap()} instead.
*/
@Override
@Deprecated
public java.util.Map<String, ServiceInfoV2> getServices() {
return getServicesMap();
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public java.util.Map<String, ServiceInfoV2> getServicesMap() {
return internalGetServices().getMap();
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public /* nullable */ ServiceInfoV2 getServicesOrDefault(
String key,
/* nullable */
ServiceInfoV2 defaultValue) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
@Override
public ServiceInfoV2 getServicesOrThrow(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<String, ServiceInfoV2> map = internalGetServices().getMap();
if (!map.containsKey(key)) {
throw new IllegalArgumentException();
}
return map.get(key);
}
public Builder clearServices() {
bitField0_ = (bitField0_ & ~0x00000004);
internalGetMutableServices().getMutableMap().clear();
return this;
}
/**
* <pre>
* A map of service information.
* </pre>
*
* <code>map<string, .org.apache.dubbo.metadata.ServiceInfoV2> services = 3;</code>
*/
public Builder removeServices(String key) {
if (key == null) {
throw new NullPointerException("map key");
}
internalGetMutableServices().getMutableMap().remove(key);
return this;
}
/**
* Use alternate mutation accessors instead.
*/
@Deprecated
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.http12.rest.Mapping;
import org.apache.dubbo.remoting.http12.rest.OpenAPI;
import org.apache.dubbo.remoting.http12.rest.OpenAPIRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.util.Collections.unmodifiableSortedSet;
import static org.apache.dubbo.common.URL.buildKey;
import static org.apache.dubbo.rpc.Constants.H2_SETTINGS_OPENAPI_PREFIX;
/**
* This service is used to expose the metadata information inside a Dubbo process.
* Typical uses include:
* 1. The Consumer queries the metadata information of the Provider to list the interfaces and each interface's configuration
* 2. The Console (dubbo-admin) queries for the metadata of a specific process, or aggregate data of all processes.
*/
@OpenAPI(hidden = "true")
public interface MetadataService {
/**
* The value of All service instances
*/
String ALL_SERVICE_INTERFACES = "*";
/**
* The contract version of {@link MetadataService}, the future update must make sure compatible.
*/
String VERSION = "1.0.0";
/**
* Gets the current Dubbo Service name
*
* @return non-null
*/
String serviceName();
/**
* Gets the version of {@link MetadataService} that always equals {@link #VERSION}
*
* @return non-null
* @see #VERSION
*/
default String version() {
return VERSION;
}
URL getMetadataURL();
/**
* the list of String that presents all Dubbo subscribed {@link URL urls}
*
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getSubscribedURLs() {
throw new UnsupportedOperationException("This operation is not supported for consumer.");
}
/**
* Get the {@link SortedSet sorted set} of String that presents all Dubbo exported {@link URL urls}
*
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs() {
return getExportedURLs(ALL_SERVICE_INTERFACES);
}
/**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the <code>serviceInterface</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface) {
return getExportedURLs(serviceInterface, null);
}
/**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code> and <code>group</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface, String group) {
return getExportedURLs(serviceInterface, group, null);
}
/**
* Get the {@link SortedSet sorted set} of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code>, <code>group</code> and <code>version</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @param version the Dubbo Service Version (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
default SortedSet<String> getExportedURLs(String serviceInterface, String group, String version) {
return getExportedURLs(serviceInterface, group, version, null);
}
/**
* Get the sorted set of String that presents the specified Dubbo exported {@link URL urls} by the
* <code>serviceInterface</code>, <code>group</code>, <code>version</code> and <code>protocol</code>
*
* @param serviceInterface The class name of Dubbo service interface
* @param group the Dubbo Service Group (optional)
* @param version the Dubbo Service Version (optional)
* @param protocol the Dubbo Service Protocol (optional)
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting the {@link URL URLs}
* @see #toSortedStrings(Stream)
* @see URL#toFullString()
*/
SortedSet<String> getExportedURLs(String serviceInterface, String group, String version, String protocol);
default Set<URL> getExportedServiceURLs() {
return Collections.emptySet();
}
/**
* Interface definition.
*
* @return
*/
default String getServiceDefinition(String interfaceName, String version, String group) {
return getServiceDefinition(buildKey(interfaceName, group, version));
}
String getServiceDefinition(String serviceKey);
MetadataInfo getMetadataInfo(String revision);
List<MetadataInfo> getMetadataInfos();
/**
* Convert the specified {@link Iterable} of {@link URL URLs} to be the {@link URL#toFullString() strings} presenting
* the {@link URL URLs}
*
* @param iterable {@link Iterable} of {@link URL}
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting
* @see URL#toFullString()
*/
static SortedSet<String> toSortedStrings(Iterable<URL> iterable) {
return toSortedStrings(StreamSupport.stream(iterable.spliterator(), false));
}
/**
* Convert the specified {@link Stream} of {@link URL URLs} to be the {@link URL#toFullString() strings} presenting
* the {@link URL URLs}
*
* @param stream {@link Stream} of {@link URL}
* @return the non-null read-only {@link SortedSet sorted set} of {@link URL#toFullString() strings} presenting
* @see URL#toFullString()
*/
static SortedSet<String> toSortedStrings(Stream<URL> stream) {
return unmodifiableSortedSet(stream.map(URL::toFullString).collect(TreeSet::new, Set::add, Set::addAll));
}
static boolean isMetadataService(String interfaceName) {
return interfaceName != null && interfaceName.equals(MetadataService.class.getName());
}
/**
* Export Metadata in Service Instance of Service Discovery
* <p>
* Used for consumer to get Service Instance Metadata
* if Registry is unsupported with publishing metadata
*
* @param instanceMetadata {@link Map} of provider Service Instance Metadata
* @since 3.0
*/
@Mapping(enabled = false)
void exportInstanceMetadata(String instanceMetadata);
/**
* Get all Metadata listener from local
* <p>
* Used for consumer to get Service Instance Metadata
* if Registry is unsupported with publishing metadata
*
* @return {@link Map} of {@link InstanceMetadataChangedListener}
* @since 3.0
*/
@Mapping(enabled = false)
Map<String, InstanceMetadataChangedListener> getInstanceMetadataChangedListenerMap();
/**
* 1. Fetch Metadata in Service Instance of Service Discovery
* 2. Add a metadata change listener
* <p>
* Used for consumer to get Service Instance Metadata
* if Registry is unsupported with publishing metadata
*
* @param consumerId consumerId
* @param listener {@link InstanceMetadataChangedListener} used to notify event
* @return {@link Map} of provider Service Instance Metadata
* @since 3.0
*/
@Mapping(enabled = false)
String getAndListenInstanceMetadata(String consumerId, InstanceMetadataChangedListener listener);
/**
* 1. Get the openAPI definition
*/
@Mapping("//${" + H2_SETTINGS_OPENAPI_PREFIX + ".path:dubbo/openapi}/{*path}")
String getOpenAPI(OpenAPIRequest request);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface MetadataConstants {
String KEY_SEPARATOR = ":";
String DEFAULT_PATH_TAG = "metadata";
String KEY_REVISION_PREFIX = "revision";
String META_DATA_STORE_TAG = ".metaData";
String METADATA_PUBLISH_DELAY_KEY = "dubbo.application.metadata.publish.delay";
int DEFAULT_METADATA_PUBLISH_DELAY = 1000;
String METADATA_PROXY_TIMEOUT_KEY = "dubbo.application.metadata.proxy.delay";
int DEFAULT_METADATA_TIMEOUT_VALUE = 5000;
String REPORT_CONSUMER_URL_KEY = "report-consumer-definition";
String PATH_SEPARATOR = "/";
String NAMESPACE_KEY = "namespace";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceV2Detector.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceV2Detector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
public class MetadataServiceV2Detector implements BuiltinServiceDetector {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(MetadataServiceV2Detector.class);
public static final String NAME = "metadataV2";
@Override
public Class<?> getService() {
if (ClassUtils.hasProtobuf()) {
return MetadataServiceV2.class;
}
logger.info("To use MetadataServiceV2, Protobuf dependencies are required. Fallback to MetadataService(V1).");
return null;
}
public static boolean support() {
return ClassUtils.hasProtobuf();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIRequest.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/OpenAPIRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* <pre>
* OpenAPI request message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.OpenAPIRequest}
*/
public final class OpenAPIRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:org.apache.dubbo.metadata.OpenAPIRequest)
OpenAPIRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use OpenAPIRequest.newBuilder() to construct.
private OpenAPIRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private OpenAPIRequest() {
group_ = "";
version_ = "";
tag_ = com.google.protobuf.LazyStringArrayList.emptyList();
service_ = com.google.protobuf.LazyStringArrayList.emptyList();
openapi_ = "";
format_ = 0;
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new OpenAPIRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIRequest_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(OpenAPIRequest.class, Builder.class);
}
private int bitField0_;
public static final int GROUP_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile Object group_ = "";
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return The group.
*/
@Override
public String getGroup() {
Object ref = group_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
group_ = s;
return s;
}
}
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return The bytes for group.
*/
@Override
public com.google.protobuf.ByteString getGroupBytes() {
Object ref = group_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
group_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile Object version_ = "";
/**
* <pre>
* The openAPI version, using a major.minor.patch versioning scheme
* e.g. 1.0.1
* </pre>
*
* <code>string version = 2;</code>
* @return The version.
*/
@Override
public String getVersion() {
Object ref = version_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
version_ = s;
return s;
}
}
/**
* <pre>
* The openAPI version, using a major.minor.patch versioning scheme
* e.g. 1.0.1
* </pre>
*
* <code>string version = 2;</code>
* @return The bytes for version.
*/
@Override
public com.google.protobuf.ByteString getVersionBytes() {
Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TAG_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList tag_ = com.google.protobuf.LazyStringArrayList.emptyList();
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @return A list containing the tag.
*/
public com.google.protobuf.ProtocolStringList getTagList() {
return tag_;
}
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @return The count of tag.
*/
public int getTagCount() {
return tag_.size();
}
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @param index The index of the element to return.
* @return The tag at the given index.
*/
public String getTag(int index) {
return tag_.get(index);
}
/**
* <pre>
* The openAPI tags. Each tag is an or condition.
* </pre>
*
* <code>repeated string tag = 3;</code>
* @param index The index of the value to return.
* @return The bytes of the tag at the given index.
*/
public com.google.protobuf.ByteString getTagBytes(int index) {
return tag_.getByteString(index);
}
public static final int SERVICE_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList service_ = com.google.protobuf.LazyStringArrayList.emptyList();
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @return A list containing the service.
*/
public com.google.protobuf.ProtocolStringList getServiceList() {
return service_;
}
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @return The count of service.
*/
public int getServiceCount() {
return service_.size();
}
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @param index The index of the element to return.
* @return The service at the given index.
*/
public String getService(int index) {
return service_.get(index);
}
/**
* <pre>
* The openAPI services. Each service is an or condition.
* </pre>
*
* <code>repeated string service = 4;</code>
* @param index The index of the value to return.
* @return The bytes of the service at the given index.
*/
public com.google.protobuf.ByteString getServiceBytes(int index) {
return service_.getByteString(index);
}
public static final int OPENAPI_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile Object openapi_ = "";
/**
* <pre>
* The openAPI specification version, using a major.minor.patch versioning scheme
* e.g. 3.0.1, 3.1.0
* The default value is '3.0.1'.
* </pre>
*
* <code>string openapi = 5;</code>
* @return The openapi.
*/
@Override
public String getOpenapi() {
Object ref = openapi_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
openapi_ = s;
return s;
}
}
/**
* <pre>
* The openAPI specification version, using a major.minor.patch versioning scheme
* e.g. 3.0.1, 3.1.0
* The default value is '3.0.1'.
* </pre>
*
* <code>string openapi = 5;</code>
* @return The bytes for openapi.
*/
@Override
public com.google.protobuf.ByteString getOpenapiBytes() {
Object ref = openapi_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
openapi_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FORMAT_FIELD_NUMBER = 6;
private int format_ = 0;
/**
* <pre>
* The format of the response.
* The default value is 'JSON'.
* </pre>
*
* <code>optional .org.apache.dubbo.metadata.OpenAPIFormat format = 6;</code>
* @return Whether the format field is set.
*/
@Override
public boolean hasFormat() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The format of the response.
* The default value is 'JSON'.
* </pre>
*
* <code>optional .org.apache.dubbo.metadata.OpenAPIFormat format = 6;</code>
* @return The enum numeric value on the wire for format.
*/
@Override
public int getFormatValue() {
return format_;
}
/**
* <pre>
* The format of the response.
* The default value is 'JSON'.
* </pre>
*
* <code>optional .org.apache.dubbo.metadata.OpenAPIFormat format = 6;</code>
* @return The format.
*/
@Override
public OpenAPIFormat getFormat() {
OpenAPIFormat result = OpenAPIFormat.forNumber(format_);
return result == null ? OpenAPIFormat.UNRECOGNIZED : result;
}
public static final int PRETTY_FIELD_NUMBER = 7;
private boolean pretty_ = false;
/**
* <pre>
* Whether to pretty print for json.
* The default value is 'false'.
* </pre>
*
* <code>optional bool pretty = 7;</code>
* @return Whether the pretty field is set.
*/
@Override
public boolean hasPretty() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Whether to pretty print for json.
* The default value is 'false'.
* </pre>
*
* <code>optional bool pretty = 7;</code>
* @return The pretty.
*/
@Override
public boolean getPretty() {
return pretty_;
}
private byte memoizedIsInitialized = -1;
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(group_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, group_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, version_);
}
for (int i = 0; i < tag_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, tag_.getRaw(i));
}
for (int i = 0; i < service_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, service_.getRaw(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(openapi_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, openapi_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeEnum(6, format_);
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeBool(7, pretty_);
}
getUnknownFields().writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(group_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, group_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, version_);
}
{
int dataSize = 0;
for (int i = 0; i < tag_.size(); i++) {
dataSize += computeStringSizeNoTag(tag_.getRaw(i));
}
size += dataSize;
size += 1 * getTagList().size();
}
{
int dataSize = 0;
for (int i = 0; i < service_.size(); i++) {
dataSize += computeStringSizeNoTag(service_.getRaw(i));
}
size += dataSize;
size += 1 * getServiceList().size();
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(openapi_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, openapi_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(6, format_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(7, pretty_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof OpenAPIRequest)) {
return super.equals(obj);
}
OpenAPIRequest other = (OpenAPIRequest) obj;
if (!getGroup().equals(other.getGroup())) {
return false;
}
if (!getVersion().equals(other.getVersion())) {
return false;
}
if (!getTagList().equals(other.getTagList())) {
return false;
}
if (!getServiceList().equals(other.getServiceList())) {
return false;
}
if (!getOpenapi().equals(other.getOpenapi())) {
return false;
}
if (hasFormat() != other.hasFormat()) {
return false;
}
if (hasFormat()) {
if (format_ != other.format_) {
return false;
}
}
if (hasPretty() != other.hasPretty()) {
return false;
}
if (hasPretty()) {
if (getPretty() != other.getPretty()) {
return false;
}
}
if (!getUnknownFields().equals(other.getUnknownFields())) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + GROUP_FIELD_NUMBER;
hash = (53 * hash) + getGroup().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
if (getTagCount() > 0) {
hash = (37 * hash) + TAG_FIELD_NUMBER;
hash = (53 * hash) + getTagList().hashCode();
}
if (getServiceCount() > 0) {
hash = (37 * hash) + SERVICE_FIELD_NUMBER;
hash = (53 * hash) + getServiceList().hashCode();
}
hash = (37 * hash) + OPENAPI_FIELD_NUMBER;
hash = (53 * hash) + getOpenapi().hashCode();
if (hasFormat()) {
hash = (37 * hash) + FORMAT_FIELD_NUMBER;
hash = (53 * hash) + format_;
}
if (hasPretty()) {
hash = (37 * hash) + PRETTY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getPretty());
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static OpenAPIRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static OpenAPIRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static OpenAPIRequest parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static OpenAPIRequest parseFrom(
com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static OpenAPIRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static OpenAPIRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static OpenAPIRequest parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static OpenAPIRequest 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 OpenAPIRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static OpenAPIRequest 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 OpenAPIRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static OpenAPIRequest parseFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(OpenAPIRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* OpenAPI request message.
* </pre>
*
* Protobuf type {@code org.apache.dubbo.metadata.OpenAPIRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:org.apache.dubbo.metadata.OpenAPIRequest)
OpenAPIRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIRequest_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return MetadataServiceV2OuterClass
.internal_static_org_apache_dubbo_metadata_OpenAPIRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(OpenAPIRequest.class, Builder.class);
}
// Construct using org.apache.dubbo.metadata.OpenAPIRequest.newBuilder()
private Builder() {}
private Builder(BuilderParent parent) {
super(parent);
}
@Override
public Builder clear() {
super.clear();
bitField0_ = 0;
group_ = "";
version_ = "";
tag_ = com.google.protobuf.LazyStringArrayList.emptyList();
service_ = com.google.protobuf.LazyStringArrayList.emptyList();
openapi_ = "";
format_ = 0;
pretty_ = false;
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return MetadataServiceV2OuterClass.internal_static_org_apache_dubbo_metadata_OpenAPIRequest_descriptor;
}
@Override
public OpenAPIRequest getDefaultInstanceForType() {
return OpenAPIRequest.getDefaultInstance();
}
@Override
public OpenAPIRequest build() {
OpenAPIRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public OpenAPIRequest buildPartial() {
OpenAPIRequest result = new OpenAPIRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(OpenAPIRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.group_ = group_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.version_ = version_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
tag_.makeImmutable();
result.tag_ = tag_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
service_.makeImmutable();
result.service_ = service_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.openapi_ = openapi_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000020) != 0)) {
result.format_ = format_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000040) != 0)) {
result.pretty_ = pretty_;
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof OpenAPIRequest) {
return mergeFrom((OpenAPIRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(OpenAPIRequest other) {
if (other == OpenAPIRequest.getDefaultInstance()) {
return this;
}
if (!other.getGroup().isEmpty()) {
group_ = other.group_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.tag_.isEmpty()) {
if (tag_.isEmpty()) {
tag_ = other.tag_;
bitField0_ |= 0x00000004;
} else {
ensureTagIsMutable();
tag_.addAll(other.tag_);
}
onChanged();
}
if (!other.service_.isEmpty()) {
if (service_.isEmpty()) {
service_ = other.service_;
bitField0_ |= 0x00000008;
} else {
ensureServiceIsMutable();
service_.addAll(other.service_);
}
onChanged();
}
if (!other.getOpenapi().isEmpty()) {
openapi_ = other.openapi_;
bitField0_ |= 0x00000010;
onChanged();
}
if (other.hasFormat()) {
setFormat(other.getFormat());
}
if (other.hasPretty()) {
setPretty(other.getPretty());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
group_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
version_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26: {
String s = input.readStringRequireUtf8();
ensureTagIsMutable();
tag_.add(s);
break;
} // case 26
case 34: {
String s = input.readStringRequireUtf8();
ensureServiceIsMutable();
service_.add(s);
break;
} // case 34
case 42: {
openapi_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
case 48: {
format_ = input.readEnum();
bitField0_ |= 0x00000020;
break;
} // case 48
case 56: {
pretty_ = input.readBool();
bitField0_ |= 0x00000040;
break;
} // case 56
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private Object group_ = "";
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return The group.
*/
public String getGroup() {
Object ref = group_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
group_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return The bytes for group.
*/
public com.google.protobuf.ByteString getGroupBytes() {
Object ref = group_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
group_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @param value The group to set.
* @return This builder for chaining.
*/
public Builder setGroup(String value) {
if (value == null) {
throw new NullPointerException();
}
group_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @return This builder for chaining.
*/
public Builder clearGroup() {
group_ = getDefaultInstance().getGroup();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* The openAPI group.
* </pre>
*
* <code>string group = 1;</code>
* @param value The bytes for group to set.
* @return This builder for chaining.
*/
public Builder setGroupBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
group_ = value;
bitField0_ |= 0x00000001;
onChanged();
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceNameMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.Set;
import java.util.TreeSet;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.of;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* This will interact with remote metadata center to find the interface-app mapping and will cache the data locally.
*
* Call variants of getCachedMapping() methods whenever need to use the mapping data.
*/
@SPI(value = "metadata", scope = APPLICATION)
public interface ServiceNameMapping extends Destroyable {
String DEFAULT_MAPPING_GROUP = "mapping";
/**
* Map the specified Dubbo service interface, group, version and protocol to current Dubbo service name
*/
boolean map(URL url);
boolean hasValidMetadataCenter();
/**
* Get the default extension of {@link ServiceNameMapping}
*
* @return non-null {@link ServiceNameMapping}
*/
static ServiceNameMapping getDefaultExtension(ScopeModel scopeModel) {
return ScopeModelUtil.getApplicationModel(scopeModel).getDefaultExtension(ServiceNameMapping.class);
}
static String buildMappingKey(URL url) {
return buildGroup(url.getServiceInterface());
}
static String buildGroup(String serviceInterface) {
// the issue : https://github.com/apache/dubbo/issues/4671
// return DEFAULT_MAPPING_GROUP + SLASH + serviceInterface;
return serviceInterface;
}
static String toStringKeys(Set<String> serviceNames) {
if (CollectionUtils.isEmpty(serviceNames)) {
return "";
}
StringBuilder builder = new StringBuilder();
for (String n : serviceNames) {
builder.append(n);
builder.append(COMMA_SEPARATOR);
}
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
static Set<String> getAppNames(String content) {
if (StringUtils.isBlank(content)) {
return emptySet();
}
return new TreeSet<>(of(content.split(COMMA_SEPARATOR))
.map(String::trim)
.filter(StringUtils::isNotEmpty)
.collect(toSet()));
}
static Set<String> getMappingByUrl(URL consumerURL) {
String providedBy = consumerURL.getParameter(RegistryConstants.PROVIDED_BY);
if (StringUtils.isBlank(providedBy)) {
return null;
}
return AbstractServiceNameMapping.parseServices(providedBy);
}
/**
* Get the latest mapping result from remote center and register listener at the same time to get notified once mapping changes.
*
* @param listener listener that will be notified on mapping change
* @return the latest mapping result from remote center
*/
Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener);
MappingListener stopListen(URL subscribeURL, MappingListener listener);
void putCachedMapping(String serviceKey, Set<String> apps);
Set<String> getMapping(URL consumerURL);
Set<String> getRemoteMapping(URL consumerURL);
Set<String> removeCachedMapping(String serviceKey);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceV2.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataServiceV2.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import java.util.concurrent.CompletableFuture;
public interface MetadataServiceV2 extends org.apache.dubbo.rpc.model.DubboStub {
String JAVA_SERVICE_NAME = "org.apache.dubbo.metadata.MetadataServiceV2";
String SERVICE_NAME = "org.apache.dubbo.metadata.MetadataServiceV2";
/**
* <pre>
* Retrieves metadata information.
* </pre>
*/
MetadataInfoV2 getMetadataInfo(MetadataRequest request);
CompletableFuture<MetadataInfoV2> getMetadataInfoAsync(MetadataRequest request);
/**
* <pre>
* Retrieves OpenAPI information.
* </pre>
*/
OpenAPIInfo getOpenAPIInfo(OpenAPIRequest request);
CompletableFuture<OpenAPIInfo> getOpenAPIInfoAsync(OpenAPIRequest request);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceInfoV2OrBuilder.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/ServiceInfoV2OrBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface ServiceInfoV2OrBuilder
extends
// @@protoc_insertion_point(interface_extends:org.apache.dubbo.metadata.ServiceInfoV2)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return The name.
*/
String getName();
/**
* <pre>
* The service name.
* </pre>
*
* <code>string name = 1;</code>
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
* <pre>
* The service group.
* </pre>
*
* <code>string group = 2;</code>
* @return The group.
*/
String getGroup();
/**
* <pre>
* The service group.
* </pre>
*
* <code>string group = 2;</code>
* @return The bytes for group.
*/
com.google.protobuf.ByteString getGroupBytes();
/**
* <pre>
* The service version.
* </pre>
*
* <code>string version = 3;</code>
* @return The version.
*/
String getVersion();
/**
* <pre>
* The service version.
* </pre>
*
* <code>string version = 3;</code>
* @return The bytes for version.
*/
com.google.protobuf.ByteString getVersionBytes();
/**
* <pre>
* The service protocol.
* </pre>
*
* <code>string protocol = 4;</code>
* @return The protocol.
*/
String getProtocol();
/**
* <pre>
* The service protocol.
* </pre>
*
* <code>string protocol = 4;</code>
* @return The bytes for protocol.
*/
com.google.protobuf.ByteString getProtocolBytes();
/**
* <pre>
* The service port.
* </pre>
*
* <code>int32 port = 5;</code>
* @return The port.
*/
int getPort();
/**
* <pre>
* The service path.
* </pre>
*
* <code>string path = 6;</code>
* @return The path.
*/
String getPath();
/**
* <pre>
* The service path.
* </pre>
*
* <code>string path = 6;</code>
* @return The bytes for path.
*/
com.google.protobuf.ByteString getPathBytes();
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
int getParamsCount();
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
boolean containsParams(String key);
/**
* Use {@link #getParamsMap()} instead.
*/
@Deprecated
java.util.Map<String, String> getParams();
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
java.util.Map<String, String> getParamsMap();
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
/* nullable */
String getParamsOrDefault(
String key,
/* nullable */
String defaultValue);
/**
* <pre>
* A map of service parameters.
* </pre>
*
* <code>map<string, string> params = 7;</code>
*/
String getParamsOrThrow(String key);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DubboMetadataServiceV2Triple.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/DubboMetadataServiceV2Triple.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PathResolver;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.ServerService;
import org.apache.dubbo.rpc.TriRpcStatus;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.StubMethodDescriptor;
import org.apache.dubbo.rpc.model.StubServiceDescriptor;
import org.apache.dubbo.rpc.service.Destroyable;
import org.apache.dubbo.rpc.stub.StubInvocationUtil;
import org.apache.dubbo.rpc.stub.StubInvoker;
import org.apache.dubbo.rpc.stub.StubMethodHandler;
import org.apache.dubbo.rpc.stub.StubSuppliers;
import org.apache.dubbo.rpc.stub.UnaryStubMethodHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import com.google.protobuf.Message;
public final class DubboMetadataServiceV2Triple {
public static final String SERVICE_NAME = MetadataServiceV2.SERVICE_NAME;
private static final StubServiceDescriptor serviceDescriptor =
new StubServiceDescriptor(SERVICE_NAME, MetadataServiceV2.class);
static {
org.apache.dubbo.rpc.protocol.tri.service.SchemaDescriptorRegistry.addSchemaDescriptor(
SERVICE_NAME, MetadataServiceV2OuterClass.getDescriptor());
StubSuppliers.addSupplier(SERVICE_NAME, DubboMetadataServiceV2Triple::newStub);
StubSuppliers.addSupplier(MetadataServiceV2.JAVA_SERVICE_NAME, DubboMetadataServiceV2Triple::newStub);
StubSuppliers.addDescriptor(SERVICE_NAME, serviceDescriptor);
StubSuppliers.addDescriptor(MetadataServiceV2.JAVA_SERVICE_NAME, serviceDescriptor);
}
@SuppressWarnings("unchecked")
public static MetadataServiceV2 newStub(Invoker<?> invoker) {
return new MetadataServiceV2Stub((Invoker<MetadataServiceV2>) invoker);
}
private static final StubMethodDescriptor getMetadataInfoMethod = new StubMethodDescriptor(
"GetMetadataInfo",
MetadataRequest.class,
MetadataInfoV2.class,
MethodDescriptor.RpcType.UNARY,
obj -> ((Message) obj).toByteArray(),
obj -> ((Message) obj).toByteArray(),
MetadataRequest::parseFrom,
MetadataInfoV2::parseFrom);
private static final StubMethodDescriptor getMetadataInfoAsyncMethod = new StubMethodDescriptor(
"GetMetadataInfo",
MetadataRequest.class,
CompletableFuture.class,
MethodDescriptor.RpcType.UNARY,
obj -> ((Message) obj).toByteArray(),
obj -> ((Message) obj).toByteArray(),
MetadataRequest::parseFrom,
MetadataInfoV2::parseFrom);
private static final StubMethodDescriptor getMetadataInfoProxyAsyncMethod = new StubMethodDescriptor(
"GetMetadataInfoAsync",
MetadataRequest.class,
MetadataInfoV2.class,
MethodDescriptor.RpcType.UNARY,
obj -> ((Message) obj).toByteArray(),
obj -> ((Message) obj).toByteArray(),
MetadataRequest::parseFrom,
MetadataInfoV2::parseFrom);
private static final StubMethodDescriptor getOpenAPIInfoMethod = new StubMethodDescriptor(
"GetOpenAPIInfo",
OpenAPIRequest.class,
OpenAPIInfo.class,
MethodDescriptor.RpcType.UNARY,
obj -> ((Message) obj).toByteArray(),
obj -> ((Message) obj).toByteArray(),
OpenAPIRequest::parseFrom,
OpenAPIInfo::parseFrom);
private static final StubMethodDescriptor getOpenAPIInfoAsyncMethod = new StubMethodDescriptor(
"GetOpenAPIInfo",
OpenAPIRequest.class,
CompletableFuture.class,
MethodDescriptor.RpcType.UNARY,
obj -> ((Message) obj).toByteArray(),
obj -> ((Message) obj).toByteArray(),
OpenAPIRequest::parseFrom,
OpenAPIInfo::parseFrom);
private static final StubMethodDescriptor getOpenAPIInfoProxyAsyncMethod = new StubMethodDescriptor(
"GetOpenAPIInfoAsync",
OpenAPIRequest.class,
OpenAPIInfo.class,
MethodDescriptor.RpcType.UNARY,
obj -> ((Message) obj).toByteArray(),
obj -> ((Message) obj).toByteArray(),
OpenAPIRequest::parseFrom,
OpenAPIInfo::parseFrom);
static {
serviceDescriptor.addMethod(getMetadataInfoMethod);
serviceDescriptor.addMethod(getMetadataInfoProxyAsyncMethod);
serviceDescriptor.addMethod(getOpenAPIInfoMethod);
serviceDescriptor.addMethod(getOpenAPIInfoProxyAsyncMethod);
}
public static class MetadataServiceV2Stub implements MetadataServiceV2, Destroyable {
private final Invoker<MetadataServiceV2> invoker;
public MetadataServiceV2Stub(Invoker<MetadataServiceV2> invoker) {
this.invoker = invoker;
}
@Override
public void $destroy() {
invoker.destroy();
}
@Override
public MetadataInfoV2 getMetadataInfo(MetadataRequest request) {
return StubInvocationUtil.unaryCall(invoker, getMetadataInfoMethod, request);
}
public CompletableFuture<MetadataInfoV2> getMetadataInfoAsync(MetadataRequest request) {
return StubInvocationUtil.unaryCall(invoker, getMetadataInfoAsyncMethod, request);
}
public void getMetadataInfo(MetadataRequest request, StreamObserver<MetadataInfoV2> responseObserver) {
StubInvocationUtil.unaryCall(invoker, getMetadataInfoMethod, request, responseObserver);
}
@Override
public OpenAPIInfo getOpenAPIInfo(OpenAPIRequest request) {
return StubInvocationUtil.unaryCall(invoker, getOpenAPIInfoMethod, request);
}
public CompletableFuture<OpenAPIInfo> getOpenAPIInfoAsync(OpenAPIRequest request) {
return StubInvocationUtil.unaryCall(invoker, getOpenAPIInfoAsyncMethod, request);
}
public void getOpenAPIInfo(OpenAPIRequest request, StreamObserver<OpenAPIInfo> responseObserver) {
StubInvocationUtil.unaryCall(invoker, getOpenAPIInfoMethod, request, responseObserver);
}
}
public abstract static class MetadataServiceV2ImplBase
implements MetadataServiceV2, ServerService<MetadataServiceV2> {
private <T, R> BiConsumer<T, StreamObserver<R>> syncToAsync(java.util.function.Function<T, R> syncFun) {
return new BiConsumer<T, StreamObserver<R>>() {
@Override
public void accept(T t, StreamObserver<R> observer) {
try {
R ret = syncFun.apply(t);
observer.onNext(ret);
observer.onCompleted();
} catch (Throwable e) {
observer.onError(e);
}
}
};
}
@Override
public CompletableFuture<MetadataInfoV2> getMetadataInfoAsync(MetadataRequest request) {
return CompletableFuture.completedFuture(getMetadataInfo(request));
}
@Override
public CompletableFuture<OpenAPIInfo> getOpenAPIInfoAsync(OpenAPIRequest request) {
return CompletableFuture.completedFuture(getOpenAPIInfo(request));
}
// This server stream type unary method is <b>only</b> used for generated stub to support async unary method.
// It will not be called if you are NOT using Dubbo3 generated triple stub and <b>DO NOT</b> implement this
// method.
public void getMetadataInfo(MetadataRequest request, StreamObserver<MetadataInfoV2> responseObserver) {
getMetadataInfoAsync(request).whenComplete((r, t) -> {
if (t != null) {
responseObserver.onError(t);
} else {
responseObserver.onNext(r);
responseObserver.onCompleted();
}
});
}
public void getOpenAPIInfo(OpenAPIRequest request, StreamObserver<OpenAPIInfo> responseObserver) {
getOpenAPIInfoAsync(request).whenComplete((r, t) -> {
if (t != null) {
responseObserver.onError(t);
} else {
responseObserver.onNext(r);
responseObserver.onCompleted();
}
});
}
@Override
public final Invoker<MetadataServiceV2> getInvoker(URL url) {
PathResolver pathResolver = url.getOrDefaultFrameworkModel()
.getExtensionLoader(PathResolver.class)
.getDefaultExtension();
Map<String, StubMethodHandler<?, ?>> handlers = new HashMap<>();
pathResolver.addNativeStub("/" + SERVICE_NAME + "/GetMetadataInfo");
pathResolver.addNativeStub("/" + SERVICE_NAME + "/GetMetadataInfoAsync");
// for compatibility
pathResolver.addNativeStub("/" + JAVA_SERVICE_NAME + "/GetMetadataInfo");
pathResolver.addNativeStub("/" + JAVA_SERVICE_NAME + "/GetMetadataInfoAsync");
pathResolver.addNativeStub("/" + SERVICE_NAME + "/GetOpenAPIInfo");
pathResolver.addNativeStub("/" + SERVICE_NAME + "/GetOpenAPIInfoAsync");
// for compatibility
pathResolver.addNativeStub("/" + JAVA_SERVICE_NAME + "/GetOpenAPIInfo");
pathResolver.addNativeStub("/" + JAVA_SERVICE_NAME + "/GetOpenAPIInfoAsync");
BiConsumer<MetadataRequest, StreamObserver<MetadataInfoV2>> getMetadataInfoFunc = this::getMetadataInfo;
handlers.put(getMetadataInfoMethod.getMethodName(), new UnaryStubMethodHandler<>(getMetadataInfoFunc));
BiConsumer<MetadataRequest, StreamObserver<MetadataInfoV2>> getMetadataInfoAsyncFunc =
syncToAsync(this::getMetadataInfo);
handlers.put(
getMetadataInfoProxyAsyncMethod.getMethodName(),
new UnaryStubMethodHandler<>(getMetadataInfoAsyncFunc));
BiConsumer<OpenAPIRequest, StreamObserver<OpenAPIInfo>> getOpenAPIInfoFunc = this::getOpenAPIInfo;
handlers.put(getOpenAPIInfoMethod.getMethodName(), new UnaryStubMethodHandler<>(getOpenAPIInfoFunc));
BiConsumer<OpenAPIRequest, StreamObserver<OpenAPIInfo>> getOpenAPIInfoAsyncFunc =
syncToAsync(this::getOpenAPIInfo);
handlers.put(
getOpenAPIInfoProxyAsyncMethod.getMethodName(),
new UnaryStubMethodHandler<>(getOpenAPIInfoAsyncFunc));
return new StubInvoker<>(this, url, MetadataServiceV2.class, handlers);
}
@Override
public MetadataInfoV2 getMetadataInfo(MetadataRequest request) {
throw unimplementedMethodException(getMetadataInfoMethod);
}
@Override
public OpenAPIInfo getOpenAPIInfo(OpenAPIRequest request) {
throw unimplementedMethodException(getOpenAPIInfoMethod);
}
@Override
public final ServiceDescriptor getServiceDescriptor() {
return serviceDescriptor;
}
private RpcException unimplementedMethodException(StubMethodDescriptor methodDescriptor) {
return TriRpcStatus.UNIMPLEMENTED
.withDescription(String.format(
"Method %s is unimplemented",
"/" + serviceDescriptor.getInterfaceName() + "/" + methodDescriptor.getMethodName()))
.asException();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingListener.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MappingListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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;
public interface MappingListener {
void onEvent(MappingChangedEvent event);
void stop();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/util/MetadataServiceVersionUtils.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/util/MetadataServiceVersionUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataInfo.ServiceInfo;
import org.apache.dubbo.metadata.MetadataInfoV2;
import org.apache.dubbo.metadata.MetadataServiceV2Detector;
import org.apache.dubbo.metadata.ServiceInfoV2;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.TRIPLE;
public class MetadataServiceVersionUtils {
public static final String V1 = "1.0.0";
public static final String V2 = "2.0.0";
public static MetadataInfoV2 toV2(MetadataInfo metadataInfo) {
if (metadataInfo == null) {
return MetadataInfoV2.newBuilder().build();
}
Map<String, ServiceInfoV2> servicesV2 = new HashMap<>();
metadataInfo.getServices().forEach((name, serviceInfo) -> servicesV2.put(name, toV2(serviceInfo)));
return MetadataInfoV2.newBuilder()
.setVersion(ifNullSetEmpty(metadataInfo.getRevision()))
.setApp(ifNullSetEmpty(metadataInfo.getApp()))
.putAllServices(servicesV2)
.build();
}
public static ServiceInfoV2 toV2(ServiceInfo serviceInfo) {
if (serviceInfo == null) {
return ServiceInfoV2.newBuilder().build();
}
return ServiceInfoV2.newBuilder()
.setVersion(ifNullSetEmpty(serviceInfo.getVersion()))
.setGroup(ifNullSetEmpty(serviceInfo.getGroup()))
.setName(ifNullSetEmpty(serviceInfo.getName()))
.setPort(serviceInfo.getPort())
.setPath(ifNullSetEmpty(serviceInfo.getPath()))
.setProtocol(ifNullSetEmpty(serviceInfo.getProtocol()))
.putAllParams(serviceInfo.getAllParams())
.build();
}
private static String ifNullSetEmpty(String value) {
return value == null ? "" : value;
}
public static MetadataInfo toV1(MetadataInfoV2 metadataInfoV2) {
Map<String, ServiceInfoV2> servicesV2Map = metadataInfoV2.getServicesMap();
Map<String, ServiceInfo> serviceMap = new HashMap<>(servicesV2Map.size());
servicesV2Map.forEach((s, serviceInfoV2) -> serviceMap.put(s, toV1(serviceInfoV2)));
return new MetadataInfo(metadataInfoV2.getApp(), metadataInfoV2.getVersion(), serviceMap);
}
public static ServiceInfo toV1(ServiceInfoV2 serviceInfoV2) {
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setGroup(serviceInfoV2.getGroup());
serviceInfo.setVersion(serviceInfoV2.getVersion());
serviceInfo.setName(serviceInfoV2.getName());
serviceInfo.setPort(serviceInfoV2.getPort());
serviceInfo.setParams(serviceInfoV2.getParamsMap());
serviceInfo.setProtocol(serviceInfoV2.getProtocol());
serviceInfo.setPath(serviceInfoV2.getPath());
return serviceInfo;
}
/**
* check if we should export MetadataService
*/
public static boolean needExportV1(ApplicationModel applicationModel) {
return !MetadataServiceV2Detector.support() || !onlyExportV2(applicationModel);
}
/**
* check if we should export MetadataServiceV2
*/
public static boolean needExportV2(ApplicationModel applicationModel) {
return MetadataServiceV2Detector.support()
&& (onlyExportV2(applicationModel) || tripleConfigured(applicationModel));
}
/**
* check if we should only export MetadataServiceV2
*/
public static boolean onlyExportV2(ApplicationModel applicationModel) {
Optional<ApplicationConfig> applicationConfig = getApplicationConfig(applicationModel);
return applicationConfig
.filter(config ->
Boolean.TRUE.equals(config.getOnlyUseMetadataV2()) && tripleConfigured(applicationModel))
.isPresent();
}
/**
* check if we can use triple as MetadataService protocol
*/
public static boolean tripleConfigured(ApplicationModel applicationModel) {
Optional<ConfigManager> configManager = Optional.ofNullable(applicationModel.getApplicationConfigManager());
Optional<ApplicationConfig> appConfig = getApplicationConfig(applicationModel);
// if user configured MetadataService protocol
if (appConfig.isPresent() && appConfig.get().getMetadataServiceProtocol() != null) {
return TRIPLE.equals(appConfig.get().getMetadataServiceProtocol());
}
// if not specified, check all protocol configs
if (configManager.isPresent()
&& CollectionUtils.isNotEmpty(configManager.get().getProtocols())) {
Collection<ProtocolConfig> protocols = configManager.get().getProtocols();
for (ProtocolConfig protocolConfig : protocols) {
if (TRIPLE.equals(protocolConfig.getName())) {
return true;
}
}
}
return false;
}
private static Optional<ApplicationConfig> getApplicationConfig(ApplicationModel applicationModel) {
Optional<ConfigManager> configManager = Optional.ofNullable(applicationModel.getApplicationConfigManager());
if (configManager.isPresent() && configManager.get().getApplication().isPresent()) {
return configManager.get().getApplication();
}
return Optional.empty();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportInstance.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.metadata.report.support.NopMetadataReport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.metadata.MetadataConstants.NAMESPACE_KEY;
import static org.apache.dubbo.metadata.report.support.Constants.METADATA_REPORT_KEY;
/**
* Repository of MetadataReport instances that can talk to remote metadata server.
*
* MetadataReport instances are initiated during the beginning of deployer.start() and used by components that
* need to interact with metadata server.
*
* If multiple metadata reports and registries need to be declared, it is recommended to group each two metadata report and registry together by giving them the same id:
* <dubbo:registry id=demo1 address="registry://"/>
* <dubbo:metadata id=demo1 address="metadata://"/>
*
* <dubbo:registry id=demo2 address="registry://"/>
* <dubbo:metadata id=demo2 address="metadata://"/>
*/
public class MetadataReportInstance implements Disposable {
private final AtomicBoolean initialized = new AtomicBoolean(false);
private String metadataType;
// mapping of registry id to metadata report instance, registry instances will use this mapping to find related
// metadata reports
private final Map<String, MetadataReport> metadataReports = new HashMap<>();
private final ApplicationModel applicationModel;
private final NopMetadataReport nopMetadataReport;
public MetadataReportInstance(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.nopMetadataReport = new NopMetadataReport();
}
public void init(List<MetadataReportConfig> metadataReportConfigs) {
if (!initialized.compareAndSet(false, true)) {
return;
}
this.metadataType = applicationModel
.getApplicationConfigManager()
.getApplicationOrElseThrow()
.getMetadataType();
if (metadataType == null) {
this.metadataType = DEFAULT_METADATA_STORAGE_TYPE;
}
MetadataReportFactory metadataReportFactory =
applicationModel.getExtensionLoader(MetadataReportFactory.class).getAdaptiveExtension();
for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) {
init(metadataReportConfig, metadataReportFactory);
}
}
private void init(MetadataReportConfig config, MetadataReportFactory metadataReportFactory) {
URL url = config.toUrl();
if (METADATA_REPORT_KEY.equals(url.getProtocol())) {
String protocol = url.getParameter(METADATA_REPORT_KEY, DEFAULT_DIRECTORY);
url = URLBuilder.from(url)
.setProtocol(protocol)
.setPort(url.getParameter(PORT_KEY, url.getPort()))
.setScopeModel(config.getScopeModel())
.removeParameter(METADATA_REPORT_KEY)
.build();
}
url = url.addParameterIfAbsent(
APPLICATION_KEY, applicationModel.getCurrentConfig().getName());
url = url.addParameterIfAbsent(
REGISTRY_LOCAL_FILE_CACHE_ENABLED,
String.valueOf(applicationModel.getCurrentConfig().getEnableFileCache()));
// RegistryConfig registryConfig = applicationModel.getConfigManager().getRegistry(relatedRegistryId)
// .orElseThrow(() -> new IllegalStateException("Registry id " + relatedRegistryId + " does not
// exist."));
MetadataReport metadataReport = metadataReportFactory.getMetadataReport(url);
if (metadataReport != null) {
metadataReports.put(getRelatedRegistryId(config, url), metadataReport);
}
}
private String getRelatedRegistryId(MetadataReportConfig config, URL url) {
String relatedRegistryId = config.getRegistry();
if (isEmpty(relatedRegistryId)) {
relatedRegistryId = config.getId();
}
if (isEmpty(relatedRegistryId)) {
relatedRegistryId = DEFAULT_KEY;
}
String namespace = url.getParameter(NAMESPACE_KEY);
if (!StringUtils.isEmpty(namespace)) {
relatedRegistryId += ":" + namespace;
}
return relatedRegistryId;
}
public Map<String, MetadataReport> getMetadataReports(boolean checked) {
return metadataReports;
}
public MetadataReport getMetadataReport(String registryKey) {
MetadataReport metadataReport = metadataReports.get(registryKey);
if (metadataReport == null && metadataReports.size() > 0) {
metadataReport = metadataReports.values().iterator().next();
}
return metadataReport;
}
public MetadataReport getNopMetadataReport() {
return nopMetadataReport;
}
public String getMetadataType() {
return metadataType;
}
public boolean isInitialized() {
return initialized.get();
}
@Override
public void destroy() {
metadataReports.forEach((k, reporter) -> reporter.destroy());
metadataReports.clear();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface MetadataReport {
/**
* Service Definition -- START
**/
void storeProviderMetadata(MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition);
String getServiceDefinition(MetadataIdentifier metadataIdentifier);
/**
* Application Metadata -- START
**/
default void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {}
default void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {}
default MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
return null;
}
/**
* deprecated or need triage
**/
void storeConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap);
List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier);
void destroy();
void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url);
void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier);
void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls);
List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
default ConfigItem getConfigItem(String key, String group) {
return new ConfigItem();
}
default boolean registerServiceAppMapping(
String serviceInterface, String defaultMappingGroup, String newConfigContent, Object ticket) {
return false;
}
default boolean registerServiceAppMapping(String serviceKey, String application, URL url) {
return false;
}
default void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {}
/**
* Service<-->Application Mapping -- START
**/
default Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
return Collections.emptySet();
}
default Set<String> getServiceAppMapping(String serviceKey, URL url) {
return Collections.emptySet();
}
boolean shouldReportDefinition();
boolean shouldReportMetadata();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class MetadataScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(MetadataReportInstance.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/MetadataReportFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.metadata.report.MetadataReportFactory.DEFAULT;
/**
*/
@SPI(DEFAULT)
public interface MetadataReportFactory {
String DEFAULT = "redis";
@Adaptive({PROTOCOL_KEY})
MetadataReport getMetadataReport(URL url);
default void destroy() {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/NopMetadataReport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class NopMetadataReport implements MetadataReport {
public NopMetadataReport() {}
@Override
public void storeProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {}
@Override
public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
return null;
}
@Override
public void storeConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap) {}
@Override
public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
return null;
}
@Override
public void destroy() {}
@Override
public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {}
@Override
public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {}
@Override
public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {}
@Override
public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return null;
}
@Override
public boolean shouldReportDefinition() {
return true;
}
@Override
public boolean shouldReportMetadata() {
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReportFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.metadata.MetadataConstants.NAMESPACE_KEY;
public abstract class AbstractMetadataReportFactory implements MetadataReportFactory {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractMetadataReportFactory.class);
private static final String EXPORT_KEY = "export";
private static final String REFER_KEY = "refer";
/**
* The lock for the acquisition process of the registry
*/
private final ReentrantLock lock = new ReentrantLock();
/**
* Registry Collection Map<metadataAddress, MetadataReport>
*/
private final Map<String, MetadataReport> serviceStoreMap = new ConcurrentHashMap<>();
@Override
public MetadataReport getMetadataReport(URL url) {
url = url.setPath(MetadataReport.class.getName()).removeParameters(EXPORT_KEY, REFER_KEY);
String key = url.toServiceString(NAMESPACE_KEY);
MetadataReport metadataReport = serviceStoreMap.get(key);
if (metadataReport != null) {
return metadataReport;
}
// Lock the metadata access process to ensure a single instance of the metadata instance
lock.lock();
try {
metadataReport = serviceStoreMap.get(key);
if (metadataReport != null) {
return metadataReport;
}
boolean check = url.getParameter(CHECK_KEY, true) && url.getPort() != 0;
try {
metadataReport = createMetadataReport(url);
} catch (Exception e) {
if (!check) {
logger.warn(PROXY_FAILED_EXPORT_SERVICE, "", "", "The metadata reporter failed to initialize", e);
} else {
throw e;
}
}
if (check && metadataReport == null) {
throw new IllegalStateException("Can not create metadata Report " + url);
}
if (metadataReport != null) {
serviceStoreMap.put(key, metadataReport);
}
return metadataReport;
} finally {
// Release the lock
lock.unlock();
}
}
@Override
public void destroy() {
lock.lock();
try {
for (MetadataReport metadataReport : serviceStoreMap.values()) {
try {
metadataReport.destroy();
} catch (Throwable ignored) {
// ignored
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", ignored.getMessage(), ignored);
}
}
serviceStoreMap.clear();
} finally {
lock.unlock();
}
}
protected abstract MetadataReport createMetadataReport(URL url);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.support;
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.ConfigUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.metadata.event.MetadataEvent;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.CYCLE_REPORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.REPORT_DEFINITION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REPORT_METADATA_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRY_PERIOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRY_TIMES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SYNC_REPORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.USER_HOME;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNEXPECTED_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.common.utils.StringUtils.replace;
import static org.apache.dubbo.metadata.report.support.Constants.CACHE;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_CYCLE_REPORT;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_PERIOD;
import static org.apache.dubbo.metadata.report.support.Constants.DEFAULT_METADATA_REPORT_RETRY_TIMES;
import static org.apache.dubbo.metadata.report.support.Constants.DUBBO_METADATA;
public abstract class AbstractMetadataReport implements MetadataReport {
protected static final String DEFAULT_ROOT = "dubbo";
protected static final int ONE_DAY_IN_MILLISECONDS = 60 * 24 * 60 * 1000;
private static final int FOUR_HOURS_IN_MILLISECONDS = 60 * 4 * 60 * 1000;
// Log output
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
// Local disk cache, where the special key value.registries records the list of metadata centers, and the others are
// the list of notified service providers
final Properties properties = new Properties();
private final ExecutorService reportCacheExecutor =
Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true));
final Map<MetadataIdentifier, Object> allMetadataReports = new ConcurrentHashMap<>(4);
private final AtomicLong lastCacheChanged = new AtomicLong();
final Map<MetadataIdentifier, Object> failedReports = new ConcurrentHashMap<>(4);
private URL reportURL;
boolean syncReport;
// Local disk cache file
File file;
private AtomicBoolean initialized = new AtomicBoolean(false);
public MetadataReportRetry metadataReportRetry;
private ScheduledExecutorService reportTimerScheduler;
private final boolean reportMetadata;
private final boolean reportDefinition;
protected ApplicationModel applicationModel;
public AbstractMetadataReport(URL reportServerURL) {
setUrl(reportServerURL);
applicationModel = reportServerURL.getOrDefaultApplicationModel();
boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
// Start file save timer
String defaultFilename = SystemPropertyConfigUtils.getSystemProperty(USER_HOME) + DUBBO_METADATA
+ reportServerURL.getApplication()
+ "-" + replace(reportServerURL.getAddress(), ":", "-")
+ CACHE;
String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename);
File file = null;
if (localCacheEnabled && ConfigUtils.isNotEmpty(filename)) {
file = new File(filename);
if (!file.exists()
&& file.getParentFile() != null
&& !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
throw new IllegalArgumentException("Invalid service store file " + file
+ ", cause: Failed to create directory " + file.getParentFile() + "!");
}
}
// if this file exists, firstly delete it.
if (!initialized.getAndSet(true) && file.exists()) {
file.delete();
}
}
this.file = file;
loadProperties();
syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false);
metadataReportRetry = new MetadataReportRetry(
reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES),
reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD));
// cycle report the data switch
if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) {
reportTimerScheduler = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("DubboMetadataReportTimer", true));
reportTimerScheduler.scheduleAtFixedRate(
this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS);
}
this.reportMetadata = reportServerURL.getParameter(REPORT_METADATA_KEY, false);
this.reportDefinition = reportServerURL.getParameter(REPORT_DEFINITION_KEY, true);
}
public URL getUrl() {
return reportURL;
}
protected void setUrl(URL url) {
if (url == null) {
throw new IllegalArgumentException("metadataReport url == null");
}
this.reportURL = url;
}
private void doSaveProperties(long version) {
if (version < lastCacheChanged.get()) {
return;
}
if (file == null) {
return;
}
// Save
try {
File lockfile = new File(file.getAbsolutePath() + ".lock");
if (!lockfile.exists()) {
lockfile.createNewFile();
}
try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
throw new IOException(
"Can not lock the metadataReport cache file " + file.getAbsolutePath()
+ ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties");
}
// Save
try {
if (!file.exists()) {
file.createNewFile();
}
Properties tmpProperties;
if (!syncReport) {
// When syncReport = false, properties.setProperty and properties.store are called from the same
// thread(reportCacheExecutor), so deep copy is not required
tmpProperties = properties;
} else {
// Using store method and setProperty method of the this.properties will cause lock contention
// under multi-threading, so deep copy a new container
tmpProperties = new Properties();
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> entry : entries) {
tmpProperties.setProperty((String) entry.getKey(), (String) entry.getValue());
}
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
tmpProperties.store(outputFile, "Dubbo metadataReport Cache");
}
} finally {
lock.release();
}
}
} catch (Throwable e) {
if (version < lastCacheChanged.get()) {
return;
} else {
reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
}
logger.warn(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"Failed to save service store file, cause: " + e.getMessage(),
e);
}
}
void loadProperties() {
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
properties.load(in);
if (logger.isInfoEnabled()) {
logger.info("Load service store file " + file + ", data: " + properties);
}
} catch (Throwable e) {
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to load service store file" + file, e);
}
}
}
private void saveProperties(MetadataIdentifier metadataIdentifier, String value, boolean add, boolean sync) {
if (file == null) {
return;
}
try {
if (add) {
properties.setProperty(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), value);
} else {
properties.remove(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY));
}
long version = lastCacheChanged.incrementAndGet();
if (sync) {
new SaveProperties(version).run();
} else {
reportCacheExecutor.execute(new SaveProperties(version));
}
} catch (Throwable t) {
logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t);
}
}
@Override
public String toString() {
return getUrl().toString();
}
private class SaveProperties implements Runnable {
private long version;
private SaveProperties(long version) {
this.version = version;
}
@Override
public void run() {
doSaveProperties(version);
}
}
@Override
public void storeProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
if (syncReport) {
storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition);
} else {
reportCacheExecutor.execute(() -> storeProviderMetadataTask(providerMetadataIdentifier, serviceDefinition));
}
}
private void storeProviderMetadataTask(
MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) {
MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(
applicationModel, providerMetadataIdentifier.getUniqueServiceName());
MetricsEventBus.post(
metadataEvent,
() -> {
boolean result = true;
try {
if (logger.isInfoEnabled()) {
logger.info("[METADATA_REGISTER] store provider metadata. Identifier : "
+ providerMetadataIdentifier + "; definition: " + serviceDefinition);
}
allMetadataReports.put(providerMetadataIdentifier, serviceDefinition);
failedReports.remove(providerMetadataIdentifier);
String data = JsonUtils.toJson(serviceDefinition);
doStoreProviderMetadata(providerMetadataIdentifier, data);
saveProperties(providerMetadataIdentifier, data, true, !syncReport);
} catch (Exception e) {
// retry again. If failed again, throw exception.
failedReports.put(providerMetadataIdentifier, serviceDefinition);
metadataReportRetry.startRetryTask();
logger.error(
PROXY_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to put provider metadata " + providerMetadataIdentifier + " in "
+ serviceDefinition + ", cause: " + e.getMessage(),
e);
result = false;
}
return result;
},
aBoolean -> aBoolean);
}
@Override
public void storeConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap) {
if (syncReport) {
storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap);
} else {
reportCacheExecutor.execute(
() -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap));
}
}
protected void storeConsumerMetadataTask(
MetadataIdentifier consumerMetadataIdentifier, Map<String, String> serviceParameterMap) {
try {
if (logger.isInfoEnabled()) {
logger.info("[METADATA_REGISTER] store consumer metadata. Identifier : " + consumerMetadataIdentifier
+ "; definition: " + serviceParameterMap);
}
allMetadataReports.put(consumerMetadataIdentifier, serviceParameterMap);
failedReports.remove(consumerMetadataIdentifier);
String data = JsonUtils.toJson(serviceParameterMap);
doStoreConsumerMetadata(consumerMetadataIdentifier, data);
saveProperties(consumerMetadataIdentifier, data, true, !syncReport);
} catch (Exception e) {
// retry again. If failed again, throw exception.
failedReports.put(consumerMetadataIdentifier, serviceParameterMap);
metadataReportRetry.startRetryTask();
logger.error(
PROXY_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to put consumer metadata " + consumerMetadataIdentifier + "; " + serviceParameterMap
+ ", cause: " + e.getMessage(),
e);
}
}
@Override
public void destroy() {
if (reportCacheExecutor != null) {
reportCacheExecutor.shutdown();
}
if (reportTimerScheduler != null) {
reportTimerScheduler.shutdown();
}
if (metadataReportRetry != null) {
metadataReportRetry.destroy();
metadataReportRetry = null;
}
}
@Override
public void saveServiceMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
if (syncReport) {
doSaveMetadata(metadataIdentifier, url);
} else {
reportCacheExecutor.execute(() -> doSaveMetadata(metadataIdentifier, url));
}
}
@Override
public void removeServiceMetadata(ServiceMetadataIdentifier metadataIdentifier) {
if (syncReport) {
doRemoveMetadata(metadataIdentifier);
} else {
reportCacheExecutor.execute(() -> doRemoveMetadata(metadataIdentifier));
}
}
@Override
public List<String> getExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
// TODO, fallback to local cache
return doGetExportedURLs(metadataIdentifier);
}
@Override
public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, Set<String> urls) {
if (syncReport) {
doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls));
} else {
reportCacheExecutor.execute(
() -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls)));
}
}
@Override
public List<String> getSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
String content = doGetSubscribedURLs(subscriberMetadataIdentifier);
return JsonUtils.toJavaList(content, String.class);
}
String getProtocol(URL url) {
String protocol = url.getSide();
protocol = protocol == null ? url.getProtocol() : protocol;
return protocol;
}
/**
* @return if need to continue
*/
public boolean retry() {
return doHandleMetadataCollection(failedReports);
}
@Override
public boolean shouldReportDefinition() {
return reportDefinition;
}
@Override
public boolean shouldReportMetadata() {
return reportMetadata;
}
private boolean doHandleMetadataCollection(Map<MetadataIdentifier, Object> metadataMap) {
if (metadataMap.isEmpty()) {
return true;
}
Iterator<Map.Entry<MetadataIdentifier, Object>> iterable =
metadataMap.entrySet().iterator();
while (iterable.hasNext()) {
Map.Entry<MetadataIdentifier, Object> item = iterable.next();
if (PROVIDER_SIDE.equals(item.getKey().getSide())) {
this.storeProviderMetadata(item.getKey(), (FullServiceDefinition) item.getValue());
} else if (CONSUMER_SIDE.equals(item.getKey().getSide())) {
this.storeConsumerMetadata(item.getKey(), (Map) item.getValue());
}
}
return false;
}
/**
* not private. just for unittest.
*/
void publishAll() {
logger.info("start to publish all metadata.");
this.doHandleMetadataCollection(allMetadataReports);
}
/**
* between 2:00 am to 6:00 am, the time is random.
*
* @return
*/
long calculateStartTime() {
Calendar calendar = Calendar.getInstance();
long nowMill = calendar.getTimeInMillis();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long subtract = calendar.getTimeInMillis() + ONE_DAY_IN_MILLISECONDS - nowMill;
return subtract
+ (FOUR_HOURS_IN_MILLISECONDS / 2)
+ ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS);
}
class MetadataReportRetry {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
final ScheduledExecutorService retryExecutor =
Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true));
volatile ScheduledFuture retryScheduledFuture;
final AtomicInteger retryCounter = new AtomicInteger(0);
// retry task schedule period
long retryPeriod;
// if no failed report, wait how many times to run retry task.
int retryTimesIfNonFail = 600;
int retryLimit;
public MetadataReportRetry(int retryTimes, int retryPeriod) {
this.retryPeriod = retryPeriod;
this.retryLimit = retryTimes;
}
void startRetryTask() {
if (retryScheduledFuture == null) {
synchronized (retryCounter) {
if (retryScheduledFuture == null) {
retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(
() -> {
// Check and connect to the metadata
try {
int times = retryCounter.incrementAndGet();
logger.info("start to retry task for metadata report. retry times:" + times);
if (retry() && times > retryTimesIfNonFail) {
cancelRetryTask();
}
if (times > retryLimit) {
cancelRetryTask();
}
} catch (Throwable t) { // Defensive fault tolerance
logger.error(
COMMON_UNEXPECTED_EXCEPTION,
"",
"",
"Unexpected error occur at failed retry, cause: " + t.getMessage(),
t);
}
},
500,
retryPeriod,
TimeUnit.MILLISECONDS);
}
}
}
}
void cancelRetryTask() {
if (retryScheduledFuture != null) {
retryScheduledFuture.cancel(false);
}
retryExecutor.shutdown();
}
void destroy() {
cancelRetryTask();
}
/**
* @deprecated only for test
*/
@Deprecated
ScheduledExecutorService getRetryExecutor() {
return retryExecutor;
}
}
private void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, List<String> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
List<String> encodedUrlList = new ArrayList<>(urls.size());
for (String url : urls) {
encodedUrlList.add(URL.encode(url));
}
doSaveSubscriberData(subscriberMetadataIdentifier, encodedUrlList);
}
protected abstract void doStoreProviderMetadata(
MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions);
protected abstract void doStoreConsumerMetadata(
MetadataIdentifier consumerMetadataIdentifier, String serviceParameterString);
protected abstract void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url);
protected abstract void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier);
protected abstract List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier);
protected abstract void doSaveSubscriberData(
SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr);
protected abstract String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier);
/**
* @deprecated only for unit test
*/
@Deprecated
protected ExecutorService getReportCacheExecutor() {
return reportCacheExecutor;
}
/**
* @deprecated only for unit test
*/
@Deprecated
protected MetadataReportRetry getMetadataReportRetry() {
return metadataReportRetry;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.metadata.report.support;
public interface Constants {
String METADATA_REPORT_KEY = "metadata";
Integer DEFAULT_METADATA_REPORT_RETRY_TIMES = 100;
Integer DEFAULT_METADATA_REPORT_RETRY_PERIOD = 3000;
Boolean DEFAULT_METADATA_REPORT_CYCLE_REPORT = true;
String CACHE = ".cache";
String DUBBO_METADATA = "/.dubbo/dubbo-metadata-";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseMetadataIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
public interface BaseMetadataIdentifier {
String getUniqueKey(KeyTypeEnum keyType);
String getIdentifierKey();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/KeyTypeEnum.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.utils.PathUtils.buildPath;
import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.metadata.MetadataConstants.KEY_SEPARATOR;
/**
* 2019-08-15
*/
public enum KeyTypeEnum {
PATH(PATH_SEPARATOR) {
public String build(String one, String... others) {
return buildPath(one, others);
}
},
UNIQUE_KEY(KEY_SEPARATOR) {
public String build(String one, String... others) {
StringBuilder keyBuilder = new StringBuilder(one);
for (String other : others) {
keyBuilder.append(separator).append(isBlank(other) ? EMPTY_STRING : other);
}
return keyBuilder.toString();
}
};
final String separator;
KeyTypeEnum(String separator) {
this.separator = separator;
}
/**
* Build Key
*
* @param one one
* @param others the others
* @return
* @since 2.7.8
*/
public abstract String build(String one, String... others);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseApplicationMetadataIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_PATH_TAG;
/**
* The Base class of MetadataIdentifier for application scope
* <p>
* 2019-08-09
*/
public class BaseApplicationMetadataIdentifier {
protected String application;
protected String getUniqueKey(KeyTypeEnum keyType, String... params) {
if (keyType == KeyTypeEnum.PATH) {
return getFilePathKey(params);
}
return getIdentifierKey(params);
}
protected String getIdentifierKey(String... params) {
return KeyTypeEnum.UNIQUE_KEY.build(application, params);
}
private String getFilePathKey(String... params) {
return getFilePathKey(DEFAULT_PATH_TAG, params);
}
private String getFilePathKey(String pathTag, String... params) {
String prefix = KeyTypeEnum.PATH.build(pathTag, application);
return KeyTypeEnum.PATH.build(prefix, params);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/SubscriberMetadataIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
/**
* 2019-08-12
*/
public class SubscriberMetadataIdentifier extends BaseApplicationMetadataIdentifier implements BaseMetadataIdentifier {
private String revision;
public SubscriberMetadataIdentifier() {}
public SubscriberMetadataIdentifier(String application, String revision) {
this.application = application;
this.revision = revision;
}
public SubscriberMetadataIdentifier(URL url) {
this.application = url.getApplication("");
this.revision = url.getParameter(REVISION_KEY, "");
}
public String getUniqueKey(KeyTypeEnum keyType) {
return super.getUniqueKey(keyType, revision);
}
public String getIdentifierKey() {
return super.getIdentifierKey(revision);
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifier.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/BaseServiceMetadataIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_PATH_TAG;
/**
* The Base class of MetadataIdentifier for service scope
* <p>
* 2019-08-09
*/
public class BaseServiceMetadataIdentifier {
protected String serviceInterface;
protected String version;
protected String group;
protected String side;
protected String getUniqueKey(KeyTypeEnum keyType, String... params) {
if (keyType == KeyTypeEnum.PATH) {
return getFilePathKey(params);
}
return getIdentifierKey(params);
}
protected String getIdentifierKey(String... params) {
String prefix = KeyTypeEnum.UNIQUE_KEY.build(serviceInterface, version, group, side);
return KeyTypeEnum.UNIQUE_KEY.build(prefix, params);
}
private String getFilePathKey(String... params) {
return getFilePathKey(DEFAULT_PATH_TAG, params);
}
private String getFilePathKey(String pathTag, String... params) {
String prefix = KeyTypeEnum.PATH.build(pathTag, toServicePath(), version, group, side);
return KeyTypeEnum.PATH.build(prefix, params);
}
private String toServicePath() {
if (ANY_VALUE.equals(serviceInterface)) {
return "";
}
return URL.encode(serviceInterface);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/ServiceMetadataIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.metadata.MetadataConstants.KEY_REVISION_PREFIX;
/**
* The ServiceMetadataIdentifier is used to store the {@link org.apache.dubbo.common.URL}
* that are from provider and consumer
* <p>
* 2019-08-09
*/
public class ServiceMetadataIdentifier extends BaseServiceMetadataIdentifier implements BaseMetadataIdentifier {
private String revision;
private String protocol;
public ServiceMetadataIdentifier() {}
public ServiceMetadataIdentifier(
String serviceInterface, String version, String group, String side, String revision, String protocol) {
this.serviceInterface = serviceInterface;
this.version = version;
this.group = group;
this.side = side;
this.revision = revision;
this.protocol = protocol;
}
public ServiceMetadataIdentifier(URL url) {
this.serviceInterface = url.getServiceInterface();
this.version = url.getVersion();
this.group = url.getGroup();
this.side = url.getSide();
this.protocol = url.getProtocol();
}
public String getUniqueKey(KeyTypeEnum keyType) {
return super.getUniqueKey(keyType, protocol, KEY_REVISION_PREFIX + revision);
}
public String getIdentifierKey() {
return super.getIdentifierKey(protocol, KEY_REVISION_PREFIX + revision);
}
public void setRevision(String revision) {
this.revision = revision;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Override
public String toString() {
return "ServiceMetadataIdentifier{" + "revision='"
+ revision + '\'' + ", protocol='"
+ protocol + '\'' + ", serviceInterface='"
+ serviceInterface + '\'' + ", version='"
+ version + '\'' + ", group='"
+ group + '\'' + ", side='"
+ side + '\'' + "} "
+ super.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/identifier/MetadataIdentifier.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.report.identifier;
import org.apache.dubbo.common.URL;
/**
* The MetadataIdentifier is used to store method descriptor.
* <p>
* The name of class is reserved because of it has been used in the previous version.
* <p>
* 2018/10/25
*/
public class MetadataIdentifier extends BaseServiceMetadataIdentifier implements BaseMetadataIdentifier {
private String application;
public MetadataIdentifier() {}
public MetadataIdentifier(String serviceInterface, String version, String group, String side, String application) {
this.serviceInterface = serviceInterface;
this.version = version;
this.group = group;
this.side = side;
this.application = application;
}
public MetadataIdentifier(URL url) {
this.serviceInterface = url.getServiceInterface();
this.version = url.getVersion();
this.group = url.getGroup();
this.side = url.getSide();
setApplication(url.getApplication());
}
public String getUniqueKey(KeyTypeEnum keyType) {
return super.getUniqueKey(keyType, application);
}
public String getIdentifierKey() {
return super.getIdentifierKey(application);
}
public String getServiceInterface() {
return serviceInterface;
}
public void setServiceInterface(String serviceInterface) {
this.serviceInterface = serviceInterface;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getUniqueServiceName() {
return serviceInterface != null ? URL.buildKey(serviceInterface, getGroup(), getVersion()) : null;
}
@Override
public String toString() {
return "MetadataIdentifier{" + "application='"
+ application + '\'' + ", serviceInterface='"
+ serviceInterface + '\'' + ", version='"
+ version + '\'' + ", group='"
+ group + '\'' + ", side='"
+ side + '\'' + '}';
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataReflectionTypeDescriberRegistrar.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataReflectionTypeDescriberRegistrar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.aot;
import org.apache.dubbo.aot.api.MemberCategory;
import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar;
import org.apache.dubbo.aot.api.TypeDescriber;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataInfoV2;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.MetadataServiceV2;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MetadataReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar {
@Override
public List<TypeDescriber> getTypeDescribers() {
List<TypeDescriber> typeDescribers = new ArrayList<>();
typeDescribers.add(buildTypeDescriberWithPublicMethod(MetadataService.class));
typeDescribers.add(buildTypeDescriberWithPublicMethod(MetadataServiceV2.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(MetadataInfo.class));
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(MetadataInfoV2.class));
return typeDescribers;
}
private TypeDescriber buildTypeDescriberWithPublicMethod(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class<?> cl) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
return new TypeDescriber(
cl.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataProxyDescriberRegistrar.java | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/aot/MetadataProxyDescriberRegistrar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.aot;
import org.apache.dubbo.aot.api.JdkProxyDescriber;
import org.apache.dubbo.aot.api.ProxyDescriberRegistrar;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.MetadataServiceV2;
import org.apache.dubbo.rpc.service.Destroyable;
import org.apache.dubbo.rpc.service.EchoService;
import java.util.ArrayList;
import java.util.List;
public class MetadataProxyDescriberRegistrar implements ProxyDescriberRegistrar {
@Override
public List<JdkProxyDescriber> getJdkProxyDescribers() {
List<JdkProxyDescriber> describers = new ArrayList<>();
describers.add(buildJdkProxyDescriber(MetadataService.class));
describers.add(buildJdkProxyDescriber(MetadataServiceV2.class));
return describers;
}
private JdkProxyDescriber buildJdkProxyDescriber(Class<?> cl) {
List<String> proxiedInterfaces = new ArrayList<>();
proxiedInterfaces.add(cl.getName());
proxiedInterfaces.add(EchoService.class.getName());
proxiedInterfaces.add(Destroyable.class.getName());
return new JdkProxyDescriber(proxiedInterfaces, null);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java | dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport4TstService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.zookeeper;
/**
* 2018/10/26
*/
public interface ZookeeperMetadataReport4TstService {
int getCounter();
void printResult(String var);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java | dubbo-metadata/dubbo-metadata-report-zookeeper/src/test/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.metadata.MappingChangedEvent;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
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 static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP;
/**
* 2018/10/9
*/
class ZookeeperMetadataReportTest {
private ZookeeperMetadataReport zookeeperMetadataReport;
private URL registryUrl;
private ZookeeperMetadataReportFactory zookeeperMetadataReportFactory;
private static String zookeeperConnectionAddress1;
@BeforeAll
public static void beforeAll() {
zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1");
}
@BeforeEach
public void setUp() throws Exception {
this.registryUrl = URL.valueOf(zookeeperConnectionAddress1);
zookeeperMetadataReportFactory = new ZookeeperMetadataReportFactory(ApplicationModel.defaultModel());
this.zookeeperMetadataReport =
(ZookeeperMetadataReport) zookeeperMetadataReportFactory.getMetadataReport(registryUrl);
}
private void deletePath(MetadataIdentifier metadataIdentifier, ZookeeperMetadataReport zookeeperMetadataReport) {
String category = zookeeperMetadataReport.toRootDir() + metadataIdentifier.getUniqueKey(KeyTypeEnum.PATH);
zookeeperMetadataReport.zkClient.delete(category);
}
@Test
void testStoreProvider() throws ClassNotFoundException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0.zk.md";
String group = null;
String application = "vic.zk.md";
MetadataIdentifier providerMetadataIdentifier =
storePrivider(zookeeperMetadataReport, interfaceName, version, group, application);
String fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(providerMetadataIdentifier));
fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier));
Assertions.assertNotNull(fileContent);
deletePath(providerMetadataIdentifier, zookeeperMetadataReport);
fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(providerMetadataIdentifier));
fileContent = waitSeconds(fileContent, 1000, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier));
Assertions.assertNull(fileContent);
providerMetadataIdentifier = storePrivider(zookeeperMetadataReport, interfaceName, version, group, application);
fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(providerMetadataIdentifier));
fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(providerMetadataIdentifier));
Assertions.assertNotNull(fileContent);
FullServiceDefinition fullServiceDefinition = JsonUtils.toJavaObject(fileContent, FullServiceDefinition.class);
Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "zkTest");
}
@Test
void testConsumer() throws ClassNotFoundException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0.zk.md";
String group = null;
String application = "vic.zk.md";
MetadataIdentifier consumerMetadataIdentifier =
storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application);
String fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier));
fileContent = waitSeconds(fileContent, 3500, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier));
Assertions.assertNotNull(fileContent);
deletePath(consumerMetadataIdentifier, zookeeperMetadataReport);
fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier));
fileContent = waitSeconds(fileContent, 1000, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier));
Assertions.assertNull(fileContent);
consumerMetadataIdentifier = storeConsumer(zookeeperMetadataReport, interfaceName, version, group, application);
fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier));
fileContent = waitSeconds(fileContent, 3000, zookeeperMetadataReport.getNodePath(consumerMetadataIdentifier));
Assertions.assertNotNull(fileContent);
Assertions.assertEquals(fileContent, "{\"paramConsumerTest\":\"zkCm\"}");
}
@Test
void testDoSaveMetadata() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-consumer-test";
String revision = "90980";
String protocol = "xxx";
URL url = generateURL(interfaceName, version, group, application);
ServiceMetadataIdentifier serviceMetadataIdentifier =
new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol);
zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url);
String fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier));
Assertions.assertNotNull(fileContent);
Assertions.assertEquals(fileContent, URL.encode(url.toFullString()));
}
@Test
void testDoRemoveMetadata() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-consumer-test";
String revision = "90980";
String protocol = "xxx";
URL url = generateURL(interfaceName, version, group, application);
ServiceMetadataIdentifier serviceMetadataIdentifier =
new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol);
zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url);
String fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier));
Assertions.assertNotNull(fileContent);
zookeeperMetadataReport.doRemoveMetadata(serviceMetadataIdentifier);
fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(serviceMetadataIdentifier));
Assertions.assertNull(fileContent);
}
@Test
void testDoGetExportedURLs() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-consumer-test";
String revision = "90980";
String protocol = "xxx";
URL url = generateURL(interfaceName, version, group, application);
ServiceMetadataIdentifier serviceMetadataIdentifier =
new ServiceMetadataIdentifier(interfaceName, version, group, "provider", revision, protocol);
zookeeperMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url);
List<String> r = zookeeperMetadataReport.doGetExportedURLs(serviceMetadataIdentifier);
Assertions.assertTrue(r.size() == 1);
String fileContent = r.get(0);
Assertions.assertNotNull(fileContent);
Assertions.assertEquals(fileContent, url.toFullString());
}
@Test
void testDoSaveSubscriberData() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-consumer-test";
String revision = "90980";
String protocol = "xxx";
URL url = generateURL(interfaceName, version, group, application);
SubscriberMetadataIdentifier subscriberMetadataIdentifier =
new SubscriberMetadataIdentifier(application, revision);
String r = JsonUtils.toJson(Arrays.asList(url.toString()));
zookeeperMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r);
String fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier));
Assertions.assertNotNull(fileContent);
Assertions.assertEquals(fileContent, r);
}
@Test
void testDoGetSubscribedURLs() throws ExecutionException, InterruptedException {
String interfaceName = "org.apache.dubbo.metadata.store.zookeeper.ZookeeperMetadataReport4TstService";
String version = "1.0.0";
String group = null;
String application = "etc-metadata-report-consumer-test";
String revision = "90980";
String protocol = "xxx";
URL url = generateURL(interfaceName, version, group, application);
SubscriberMetadataIdentifier subscriberMetadataIdentifier =
new SubscriberMetadataIdentifier(application, revision);
String r = JsonUtils.toJson(Arrays.asList(url.toString()));
zookeeperMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r);
String fileContent = zookeeperMetadataReport.zkClient.getContent(
zookeeperMetadataReport.getNodePath(subscriberMetadataIdentifier));
Assertions.assertNotNull(fileContent);
Assertions.assertEquals(fileContent, r);
}
private MetadataIdentifier storePrivider(
MetadataReport zookeeperMetadataReport,
String interfaceName,
String version,
String group,
String application)
throws ClassNotFoundException, InterruptedException {
URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName
+ "?paramTest=zkTest&version=" + version + "&application=" + application
+ (group == null ? "" : "&group=" + group));
MetadataIdentifier providerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application);
Class interfaceClass = Class.forName(interfaceName);
FullServiceDefinition fullServiceDefinition =
ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters());
zookeeperMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition);
Thread.sleep(2000);
return providerMetadataIdentifier;
}
private MetadataIdentifier storeConsumer(
MetadataReport zookeeperMetadataReport,
String interfaceName,
String version,
String group,
String application)
throws ClassNotFoundException, InterruptedException {
URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName
+ "?version=" + version + "&application=" + application + (group == null ? "" : "&group=" + group));
MetadataIdentifier consumerMetadataIdentifier =
new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application);
Class interfaceClass = Class.forName(interfaceName);
Map<String, String> tmp = new HashMap<>();
tmp.put("paramConsumerTest", "zkCm");
zookeeperMetadataReport.storeConsumerMetadata(consumerMetadataIdentifier, tmp);
Thread.sleep(2000);
return consumerMetadataIdentifier;
}
private String waitSeconds(String value, long moreTime, String path) throws InterruptedException {
if (value == null) {
Thread.sleep(moreTime);
return zookeeperMetadataReport.zkClient.getContent(path);
}
return value;
}
private URL generateURL(String interfaceName, String version, String group, String application) {
URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":8989/" + interfaceName
+ "?paramTest=etcdTest&version="
+ version + "&application="
+ application + (group == null ? "" : "&group=" + group));
return url;
}
@Test
void testMapping() throws InterruptedException {
String serviceKey = ZookeeperMetadataReportTest.class.getName();
URL url = URL.valueOf("test://127.0.0.1:8888/" + serviceKey);
String appNames = "demo1,demo2";
CountDownLatch latch = new CountDownLatch(1);
Set<String> serviceAppMapping = zookeeperMetadataReport.getServiceAppMapping(
serviceKey,
new MappingListener() {
@Override
public void onEvent(MappingChangedEvent event) {
Set<String> apps = event.getApps();
Assertions.assertEquals(apps.size(), 2);
Assertions.assertTrue(apps.contains("demo1"));
Assertions.assertTrue(apps.contains("demo2"));
latch.countDown();
}
@Override
public void stop() {}
},
url);
Assertions.assertTrue(serviceAppMapping.isEmpty());
ConfigItem configItem = zookeeperMetadataReport.getConfigItem(serviceKey, DEFAULT_MAPPING_GROUP);
zookeeperMetadataReport.registerServiceAppMapping(
serviceKey, DEFAULT_MAPPING_GROUP, appNames, configItem.getTicket());
latch.await();
}
@Test
void testAppMetadata() {
String serviceKey = ZookeeperMetadataReportTest.class.getName();
String appName = "demo";
URL url = URL.valueOf("test://127.0.0.1:8888/" + serviceKey);
MetadataInfo metadataInfo = new MetadataInfo(appName);
metadataInfo.addService(url);
SubscriberMetadataIdentifier identifier =
new SubscriberMetadataIdentifier(appName, metadataInfo.calAndGetRevision());
MetadataInfo appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap());
Assertions.assertNull(appMetadata);
zookeeperMetadataReport.publishAppMetadata(identifier, metadataInfo);
appMetadata = zookeeperMetadataReport.getAppMetadata(identifier, Collections.emptyMap());
Assertions.assertNotNull(appMetadata);
Assertions.assertEquals(appMetadata.calAndGetRevision(), metadataInfo.calAndGetRevision());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java | dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MappingChangedEvent;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReport;
import org.apache.dubbo.remoting.zookeeper.curator5.DataListener;
import org.apache.dubbo.remoting.zookeeper.curator5.EventType;
import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.zookeeper.data.Stat;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
import static org.apache.dubbo.metadata.ServiceNameMapping.DEFAULT_MAPPING_GROUP;
import static org.apache.dubbo.metadata.ServiceNameMapping.getAppNames;
public class ZookeeperMetadataReport extends AbstractMetadataReport {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ZookeeperMetadataReport.class);
private final String root;
ZookeeperClient zkClient;
private ConcurrentMap<String, MappingDataListener> casListenerMap = new ConcurrentHashMap<>();
public ZookeeperMetadataReport(URL url, ZookeeperClientManager zookeeperClientManager) {
super(url);
if (url.isAnyHost()) {
throw new IllegalStateException("registry address == null");
}
String group = url.getGroup(DEFAULT_ROOT);
if (!group.startsWith(PATH_SEPARATOR)) {
group = PATH_SEPARATOR + group;
}
this.root = group;
zkClient = zookeeperClientManager.connect(url);
}
protected String toRootDir() {
if (root.equals(PATH_SEPARATOR)) {
return root;
}
return root + PATH_SEPARATOR;
}
@Override
protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) {
storeMetadata(providerMetadataIdentifier, serviceDefinitions);
}
@Override
protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) {
storeMetadata(consumerMetadataIdentifier, value);
}
@Override
protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) {
zkClient.createOrUpdate(getNodePath(metadataIdentifier), URL.encode(url.toFullString()), false);
}
@Override
protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) {
zkClient.delete(getNodePath(metadataIdentifier));
}
@Override
protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) {
String content = zkClient.getContent(getNodePath(metadataIdentifier));
if (StringUtils.isEmpty(content)) {
return Collections.emptyList();
}
return new ArrayList<>(Collections.singletonList(URL.decode(content)));
}
@Override
protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) {
zkClient.createOrUpdate(getNodePath(subscriberMetadataIdentifier), urls, false);
}
@Override
protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) {
return zkClient.getContent(getNodePath(subscriberMetadataIdentifier));
}
@Override
public String getServiceDefinition(MetadataIdentifier metadataIdentifier) {
return zkClient.getContent(getNodePath(metadataIdentifier));
}
private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) {
zkClient.createOrUpdate(getNodePath(metadataIdentifier), v, false);
}
String getNodePath(BaseMetadataIdentifier metadataIdentifier) {
return toRootDir() + metadataIdentifier.getUniqueKey(KeyTypeEnum.PATH);
}
@Override
public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
String path = getNodePath(identifier);
if (StringUtils.isBlank(zkClient.getContent(path)) && StringUtils.isNotEmpty(metadataInfo.getContent())) {
zkClient.createOrUpdate(path, metadataInfo.getContent(), false);
}
}
@Override
public void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) {
String path = getNodePath(identifier);
if (StringUtils.isNotEmpty(zkClient.getContent(path))) {
zkClient.delete(path);
}
}
@Override
public MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) {
String content = zkClient.getContent(getNodePath(identifier));
return JsonUtils.toJavaObject(content, MetadataInfo.class);
}
@Override
public Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) {
String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey);
MappingDataListener mappingDataListener = ConcurrentHashMapUtils.computeIfAbsent(casListenerMap, path, _k -> {
MappingDataListener newMappingListener = new MappingDataListener(serviceKey, path);
zkClient.addDataListener(path, newMappingListener);
return newMappingListener;
});
mappingDataListener.addListener(listener);
return getAppNames(zkClient.getContent(path));
}
@Override
public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) {
String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey);
if (null != casListenerMap.get(path)) {
removeCasServiceMappingListener(path, listener);
}
}
@Override
public Set<String> getServiceAppMapping(String serviceKey, URL url) {
String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey);
return getAppNames(zkClient.getContent(path));
}
@Override
public ConfigItem getConfigItem(String serviceKey, String group) {
String path = buildPathKey(group, serviceKey);
return zkClient.getConfigItem(path);
}
@Override
public boolean registerServiceAppMapping(String key, String group, String content, Object ticket) {
try {
if (ticket != null && !(ticket instanceof Stat)) {
throw new IllegalArgumentException("zookeeper publishConfigCas requires stat type ticket");
}
String pathKey = buildPathKey(group, key);
zkClient.createOrUpdate(pathKey, content, false, ticket == null ? null : ((Stat) ticket).getVersion());
return true;
} catch (Exception e) {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "zookeeper publishConfigCas failed.", e);
return false;
}
}
@Override
public void destroy() {
super.destroy();
// release zk client reference, but should not close it
zkClient = null;
}
private String buildPathKey(String group, String serviceKey) {
return toRootDir() + group + PATH_SEPARATOR + serviceKey;
}
private void removeCasServiceMappingListener(String path, MappingListener listener) {
MappingDataListener mappingDataListener = casListenerMap.get(path);
mappingDataListener.removeListener(listener);
if (mappingDataListener.isEmpty()) {
zkClient.removeDataListener(path, mappingDataListener);
casListenerMap.remove(path, mappingDataListener);
}
}
private static class MappingDataListener implements DataListener {
private String serviceKey;
private String path;
private Set<MappingListener> listeners;
public MappingDataListener(String serviceKey, String path) {
this.serviceKey = serviceKey;
this.path = path;
this.listeners = new HashSet<>();
}
public void addListener(MappingListener listener) {
this.listeners.add(listener);
}
public void removeListener(MappingListener listener) {
this.listeners.remove(listener);
}
public boolean isEmpty() {
return listeners.isEmpty();
}
@Override
public void dataChanged(String path, Object value, EventType eventType) {
if (!this.path.equals(path)) {
return;
}
if (EventType.NodeCreated != eventType && EventType.NodeDataChanged != eventType) {
return;
}
Set<String> apps = getAppNames((String) value);
MappingChangedEvent event = new MappingChangedEvent(serviceKey, apps);
listeners.forEach(mappingListener -> mappingListener.onEvent(event));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java | dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReportFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF 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.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.DisableInject;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory;
import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* ZookeeperRegistryFactory.
*/
public class ZookeeperMetadataReportFactory extends AbstractMetadataReportFactory {
private ZookeeperClientManager zookeeperClientManager;
public ZookeeperMetadataReportFactory(ApplicationModel applicationModel) {
this.zookeeperClientManager = ZookeeperClientManager.getInstance(applicationModel);
}
@DisableInject
public void setZookeeperTransporter(ZookeeperClientManager zookeeperClientManager) {
this.zookeeperClientManager = zookeeperClientManager;
}
@Override
public MetadataReport createMetadataReport(URL url) {
return new ZookeeperMetadataReport(url, zookeeperClientManager);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilderTest.java | 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;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/GooglePB.java | 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;
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-definition-protobuf/src/test/java/org/apache/dubbo/metadata/definition/protobuf/model/ServiceInterface.java | 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);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metadata/dubbo-metadata-definition-protobuf/src/main/java/org/apache/dubbo/metadata/definition/protobuf/ProtobufTypeBuilder.java | 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 match[" + 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]);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultMultipleSerialization.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultMultipleSerialization.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import org.apache.dubbo.common.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DefaultMultipleSerialization implements MultipleSerialization {
@Override
public void serialize(URL url, String serializeType, Class<?> clz, Object obj, OutputStream os) throws IOException {
serializeType = convertHessian(serializeType);
final Serialization serialization = url.getOrDefaultFrameworkModel()
.getExtensionLoader(Serialization.class)
.getExtension(serializeType);
final ObjectOutput serialize = serialization.serialize(null, os);
serialize.writeObject(obj);
serialize.flushBuffer();
}
@Override
public Object deserialize(URL url, String serializeType, Class<?> clz, InputStream os)
throws IOException, ClassNotFoundException {
serializeType = convertHessian(serializeType);
final Serialization serialization = url.getOrDefaultFrameworkModel()
.getExtensionLoader(Serialization.class)
.getExtension(serializeType);
final ObjectInput in = serialization.deserialize(null, os);
return in.readObject(clz);
}
private String convertHessian(String ser) {
if (ser.equals("hessian4")) {
return "hessian2";
}
return ser;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DataInput.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DataInput.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import java.io.IOException;
/**
* Basic data type input interface.
*/
public interface DataInput {
/**
* Read boolean.
*
* @return boolean.
* @throws IOException
*/
boolean readBool() throws IOException;
/**
* Read byte.
*
* @return byte value.
* @throws IOException
*/
byte readByte() throws IOException;
/**
* Read short integer.
*
* @return short.
* @throws IOException
*/
short readShort() throws IOException;
/**
* Read integer.
*
* @return integer.
* @throws IOException
*/
int readInt() throws IOException;
/**
* Read long.
*
* @return long.
* @throws IOException
*/
long readLong() throws IOException;
/**
* Read float.
*
* @return float.
* @throws IOException
*/
float readFloat() throws IOException;
/**
* Read double.
*
* @return double.
* @throws IOException
*/
double readDouble() throws IOException;
/**
* Read UTF-8 string.
*
* @return string.
* @throws IOException
*/
String readUTF() throws IOException;
/**
* Read byte array.
*
* @return byte array.
* @throws IOException
*/
byte[] readBytes() throws IOException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultSerializationExceptionWrapper.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DefaultSerializationExceptionWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import org.apache.dubbo.common.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.Map;
public class DefaultSerializationExceptionWrapper implements Serialization {
private final Serialization serialization;
public DefaultSerializationExceptionWrapper(Serialization serialization) {
if (serialization == null) {
throw new IllegalArgumentException("serialization == null");
}
this.serialization = serialization;
}
@Override
public byte getContentTypeId() {
return serialization.getContentTypeId();
}
@Override
public String getContentType() {
return serialization.getContentType();
}
@Override
public ObjectOutput serialize(URL url, OutputStream output) throws IOException {
ObjectOutput objectOutput = serialization.serialize(url, output);
return new ProxyObjectOutput(objectOutput);
}
@Override
public ObjectInput deserialize(URL url, InputStream input) throws IOException {
ObjectInput objectInput = serialization.deserialize(url, input);
return new ProxyObjectInput(objectInput);
}
static class ProxyObjectInput implements ObjectInput {
private final ObjectInput target;
public ProxyObjectInput(ObjectInput target) {
this.target = target;
}
@Override
public boolean readBool() throws IOException {
try {
return target.readBool();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public byte readByte() throws IOException {
try {
return target.readByte();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public short readShort() throws IOException {
try {
return target.readShort();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public int readInt() throws IOException {
try {
return target.readInt();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public long readLong() throws IOException {
try {
return target.readLong();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public float readFloat() throws IOException {
try {
return target.readFloat();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public double readDouble() throws IOException {
try {
return target.readDouble();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public String readUTF() throws IOException {
try {
return target.readUTF();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public byte[] readBytes() throws IOException {
try {
return target.readBytes();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public Object readObject() throws IOException, ClassNotFoundException {
try {
return target.readObject();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public <T> T readObject(Class<T> cls) throws IOException, ClassNotFoundException {
try {
return target.readObject(cls);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public <T> T readObject(Class<T> cls, Type type) throws IOException, ClassNotFoundException {
try {
return target.readObject(cls, type);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public Throwable readThrowable() throws IOException {
try {
return target.readThrowable();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public String readEvent() throws IOException {
try {
return target.readEvent();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public Map<String, Object> readAttachments() throws IOException, ClassNotFoundException {
try {
return target.readAttachments();
} catch (Exception e) {
if (e instanceof ClassNotFoundException) {
throw e;
}
throw handleToIOException(e);
}
}
}
static class ProxyObjectOutput implements ObjectOutput {
private final ObjectOutput target;
public ProxyObjectOutput(ObjectOutput target) {
this.target = target;
}
@Override
public void writeBool(boolean v) throws IOException {
try {
target.writeBool(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeByte(byte v) throws IOException {
try {
target.writeByte(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeShort(short v) throws IOException {
try {
target.writeShort(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeInt(int v) throws IOException {
try {
target.writeInt(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeLong(long v) throws IOException {
try {
target.writeLong(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeFloat(float v) throws IOException {
try {
target.writeFloat(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeDouble(double v) throws IOException {
try {
target.writeDouble(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeUTF(String v) throws IOException {
try {
target.writeUTF(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeBytes(byte[] v) throws IOException {
try {
target.writeBytes(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeBytes(byte[] v, int off, int len) throws IOException {
try {
target.writeBytes(v);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void flushBuffer() throws IOException {
try {
target.flushBuffer();
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeObject(Object obj) throws IOException {
try {
target.writeObject(obj);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeThrowable(Throwable obj) throws IOException {
try {
target.writeThrowable(obj);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeEvent(String data) throws IOException {
try {
target.writeEvent(data);
} catch (Exception e) {
throw handleToIOException(e);
}
}
@Override
public void writeAttachments(Map<String, Object> attachments) throws IOException {
try {
target.writeAttachments(attachments);
} catch (Exception e) {
throw handleToIOException(e);
}
}
}
private static IOException handleToIOException(Exception e) {
if (!(e instanceof IOException)) {
return new IOException(new SerializationException(e));
}
return (IOException) e;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectInput.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectInput.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Object input interface.
*/
public interface ObjectInput extends DataInput {
/**
* Consider use {@link #readObject(Class)} or {@link #readObject(Class, Type)} where possible
*
* @return object
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if an ClassNotFoundException occurs
*/
Object readObject() throws IOException, ClassNotFoundException;
/**
* read object
*
* @param cls object class
* @return object
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if an ClassNotFoundException occurs
*/
<T> T readObject(Class<T> cls) throws IOException, ClassNotFoundException;
/**
* read object
*
* @param cls object class
* @param type object type
* @return object
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if an ClassNotFoundException occurs
*/
<T> T readObject(Class<T> cls, Type type) throws IOException, ClassNotFoundException;
/**
* The following methods are customized for the requirement of Dubbo's RPC protocol implementation. Legacy protocol
* implementation will try to write Map, Throwable and Null value directly to the stream, which does not meet the
* restrictions of all serialization protocols.
*
* <p>
* See how ProtobufSerialization, KryoSerialization implemented these methods for more details.
* <p>
* <p>
* The binding of RPC protocol and biz serialization protocol is not a good practice. Encoding of RPC protocol
* should be highly independent and portable, easy to cross platforms and languages, for example, like the http headers,
* restricting the content of headers / attachments to Ascii strings and uses ISO_8859_1 to encode them.
* https://tools.ietf.org/html/rfc7540#section-8.1.2
*/
default Throwable readThrowable() throws IOException, ClassNotFoundException {
Object obj = readObject();
if (!(obj instanceof Throwable)) {
throw new IOException("Response data error, expect Throwable, but get " + obj.getClass());
}
return (Throwable) obj;
}
default String readEvent() throws IOException, ClassNotFoundException {
return readUTF();
}
default Map<String, Object> readAttachments() throws IOException, ClassNotFoundException {
return readObject(Map.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectOutput.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/ObjectOutput.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import java.io.IOException;
import java.util.Map;
/**
* Object output interface.
*/
public interface ObjectOutput extends DataOutput {
/**
* write object.
*
* @param obj object.
*/
void writeObject(Object obj) throws IOException;
/**
* The following methods are customized for the requirement of Dubbo's RPC protocol implementation. Legacy protocol
* implementation will try to write Map, Throwable and Null value directly to the stream, which does not meet the
* restrictions of all serialization protocols.
*
* <p>
* See how ProtobufSerialization, KryoSerialization implemented these methods for more details.
* <p>
*
* The binding of RPC protocol and biz serialization protocol is not a good practice. Encoding of RPC protocol
* should be highly independent and portable, easy to cross platforms and languages, for example, like the http headers,
* restricting the content of headers / attachments to Ascii strings and uses ISO_8859_1 to encode them.
* https://tools.ietf.org/html/rfc7540#section-8.1.2
*/
default void writeThrowable(Throwable obj) throws IOException {
writeObject(obj);
}
default void writeEvent(String data) throws IOException {
writeUTF(data);
}
default void writeAttachments(Map<String, Object> attachments) throws IOException {
writeObject(attachments);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DataOutput.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/DataOutput.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import java.io.IOException;
/**
* Basic data type output interface.
*/
public interface DataOutput {
/**
* Write boolean.
*
* @param v value.
* @throws IOException
*/
void writeBool(boolean v) throws IOException;
/**
* Write byte.
*
* @param v value.
* @throws IOException
*/
void writeByte(byte v) throws IOException;
/**
* Write short.
*
* @param v value.
* @throws IOException
*/
void writeShort(short v) throws IOException;
/**
* Write integer.
*
* @param v value.
* @throws IOException
*/
void writeInt(int v) throws IOException;
/**
* Write long.
*
* @param v value.
* @throws IOException
*/
void writeLong(long v) throws IOException;
/**
* Write float.
*
* @param v value.
* @throws IOException
*/
void writeFloat(float v) throws IOException;
/**
* Write double.
*
* @param v value.
* @throws IOException
*/
void writeDouble(double v) throws IOException;
/**
* Write string.
*
* @param v value.
* @throws IOException
*/
void writeUTF(String v) throws IOException;
/**
* Write byte array.
*
* @param v value.
* @throws IOException
*/
void writeBytes(byte[] v) throws IOException;
/**
* Write byte array.
*
* @param v value.
* @param off the start offset in the data.
* @param len the number of bytes that are written.
* @throws IOException
*/
void writeBytes(byte[] v, int off, int len) throws IOException;
/**
* Flush buffer.
*
* @throws IOException
*/
void flushBuffer() throws IOException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Serialization.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Serialization.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Serialization strategy interface that specifies a serializer. (SPI, Singleton, ThreadSafe)
*
* The default extension is hessian2 and the default serialization implementation of the dubbo protocol.
* <pre>
* e.g. <dubbo:protocol serialization="xxx" />
* </pre>
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface Serialization {
/**
* Get content type unique id, recommended that custom implementations use values different with
* any value of {@link Constants} and don't greater than ExchangeCodec.SERIALIZATION_MASK (31)
* because dubbo protocol use 5 bits to record serialization ID in header.
*
* @return content type id
*/
byte getContentTypeId();
/**
* Get content type
*
* @return content type
*/
String getContentType();
/**
* Get a serialization implementation instance
*
* @param url URL address for the remote service
* @param output the underlying output stream
* @return serializer
* @throws IOException
*/
@Adaptive
ObjectOutput serialize(URL url, OutputStream output) throws IOException;
/**
* Get a deserialization implementation instance
*
* @param url URL address for the remote service
* @param input the underlying input stream
* @return deserializer
* @throws IOException
*/
@Adaptive
ObjectInput deserialize(URL url, InputStream input) throws IOException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Cleanable.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Cleanable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
/**
* Interface defines that the object is cleanable.
*/
public interface Cleanable {
/**
* Implementations must implement this cleanup method
*/
void cleanup();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationScopeModelInitializer.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import org.apache.dubbo.common.serialize.support.PreferSerializationProviderImpl;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class SerializationScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
frameworkModel.getBeanFactory().registerBean(PreferSerializationProviderImpl.class);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/Constants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
public interface Constants {
byte HESSIAN2_SERIALIZATION_ID = 2;
byte JAVA_SERIALIZATION_ID = 3;
byte COMPACTED_JAVA_SERIALIZATION_ID = 4;
byte FASTJSON_SERIALIZATION_ID = 6;
byte NATIVE_JAVA_SERIALIZATION_ID = 7;
byte KRYO_SERIALIZATION_ID = 8;
byte FST_SERIALIZATION_ID = 9;
byte NATIVE_HESSIAN_SERIALIZATION_ID = 10;
byte PROTOSTUFF_SERIALIZATION_ID = 12;
byte AVRO_SERIALIZATION_ID = 11;
byte GSON_SERIALIZATION_ID = 16;
byte JACKSON_SERIALIZATION_ID = 18;
byte PROTOBUF_JSON_SERIALIZATION_ID = 21;
byte PROTOBUF_SERIALIZATION_ID = 22;
byte FASTJSON2_SERIALIZATION_ID = 23;
byte KRYO_SERIALIZATION2_ID = 25;
byte MSGPACK_SERIALIZATION_ID = 27;
byte FURY_SERIALIZATION_ID = 28;
byte CUSTOM_MESSAGE_PACK_ID = 31;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/MultipleSerialization.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/MultipleSerialization.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface MultipleSerialization {
void serialize(URL url, String serializeType, Class<?> clz, Object obj, OutputStream os) throws IOException;
Object deserialize(URL url, String serializeType, Class<?> clz, InputStream os)
throws IOException, ClassNotFoundException;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationException.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/SerializationException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize;
/**
* Serialized runtime exceptions, internal flow,
* will be converted into general exceptions and added to serialization tags when returning to rpc
*/
public class SerializationException extends Exception {
private static final long serialVersionUID = -3160452149606778709L;
public SerializationException(String msg) {
super(msg);
}
public SerializationException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize.support;
import java.util.HashMap;
import java.util.Map;
/**
* Provide a unified serialization registry, this class used for {@code dubbo-serialization-fst}
* and {@code dubbo-serialization-kryo}, it will register some classes at startup time (for example {@link AbstractKryoFactory#create})
*/
public abstract class SerializableClassRegistry {
private static final Map<Class<?>, Object> REGISTRATIONS = new HashMap<>();
/**
* only supposed to be called at startup time
*
* @param clazz object type
*/
public static void registerClass(Class<?> clazz) {
registerClass(clazz, null);
}
/**
* only supposed to be called at startup time
*
* @param clazz object type
* @param serializer object serializer
*/
public static void registerClass(Class<?> clazz, Object serializer) {
if (clazz == null) {
throw new IllegalArgumentException("Class registered to kryo cannot be null!");
}
REGISTRATIONS.put(clazz, serializer);
}
/**
* get registered classes
*
* @return class serializer
* */
public static Map<Class<?>, Object> getRegisteredClasses() {
return REGISTRATIONS;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializationOptimizer.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/SerializationOptimizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize.support;
import java.util.Collection;
/**
* Interface defining serialization optimizer, there are nothing implementations for now.
*/
public interface SerializationOptimizer {
/**
* Get serializable classes
*
* @return serializable classes
* */
Collection<Class<?>> getSerializableClasses();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/PreferSerializationProviderImpl.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/PreferSerializationProviderImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize.support;
import org.apache.dubbo.common.serialization.PreferSerializationProvider;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PreferSerializationProviderImpl implements PreferSerializationProvider {
private final String preferSerialization;
public PreferSerializationProviderImpl(FrameworkModel frameworkModel) {
List<String> defaultSerializations = Arrays.asList("hessian2", "fastjson2");
this.preferSerialization = defaultSerializations.stream()
.filter(s ->
frameworkModel.getExtensionLoader(Serialization.class).hasExtension(s))
.collect(Collectors.joining(","));
}
@Override
public String getPreferSerialization() {
return preferSerialization;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/DefaultSerializationSelector.java | dubbo-serialization/dubbo-serialization-api/src/main/java/org/apache/dubbo/common/serialize/support/DefaultSerializationSelector.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.serialize.support;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_DEFAULT_REMOTING_SERIALIZATION_PROPERTY;
public class DefaultSerializationSelector {
private static final String DEFAULT_REMOTING_SERIALIZATION_PROPERTY = "hessian2";
private static final String DEFAULT_REMOTING_SERIALIZATION;
static {
String fromProperty =
SystemPropertyConfigUtils.getSystemProperty(DUBBO_DEFAULT_REMOTING_SERIALIZATION_PROPERTY);
if (fromProperty != null) {
DEFAULT_REMOTING_SERIALIZATION = fromProperty;
} else {
String fromEnv = System.getenv(DUBBO_DEFAULT_REMOTING_SERIALIZATION_PROPERTY);
if (fromEnv != null) {
DEFAULT_REMOTING_SERIALIZATION = fromEnv;
} else {
DEFAULT_REMOTING_SERIALIZATION = DEFAULT_REMOTING_SERIALIZATION_PROPERTY;
}
}
}
public static String getDefaultRemotingSerialization() {
return DEFAULT_REMOTING_SERIALIZATION;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/com/example/test/TestPojo.java | dubbo-serialization/dubbo-serialization-fastjson2/src/test/java/com/example/test/TestPojo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.test;
import java.io.Serializable;
import java.util.Objects;
public class TestPojo implements Serializable {
private final String data;
public TestPojo(String data) {
this.data = data;
}
@Override
public String toString() {
throw new IllegalAccessError();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestPojo testPojo = (TestPojo) o;
return Objects.equals(data, testPojo.data);
}
@Override
public int hashCode() {
return Objects.hash(data);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.