core: add accessor for bare method name in MethodDescriptor (#7339)

Added getBareMethodName and extractBareMethodName for accessing the unqualified method name.
This commit is contained in:
Philipp Kern 2020-09-03 23:27:18 +02:00 committed by GitHub
parent 3493347581
commit 07012421ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 60 additions and 0 deletions

View File

@ -262,6 +262,17 @@ public final class MethodDescriptor<ReqT, RespT> {
return serviceName;
}
/**
* A convenience method for {@code extractBareMethodName(getFullMethodName())}.
*
* @since 1.32.0
*/
@Nullable
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/5635")
public String getBareMethodName() {
return extractBareMethodName(fullMethodName);
}
/**
* Parse a response payload from the given {@link InputStream}.
*
@ -398,6 +409,22 @@ public final class MethodDescriptor<ReqT, RespT> {
return fullMethodName.substring(0, index);
}
/**
* Extract the method name out of a fully qualified method name. May return {@code null}
* if the input is malformed, but you cannot rely on it for the validity of the input.
*
* @since 1.32.0
*/
@Nullable
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/5635")
public static String extractBareMethodName(String fullMethodName) {
int index = checkNotNull(fullMethodName, "fullMethodName").lastIndexOf('/');
if (index == -1) {
return null;
}
return fullMethodName.substring(index + 1);
}
/**
* Creates a new builder for a {@link MethodDescriptor}.
*

View File

@ -177,6 +177,39 @@ public class MethodDescriptorTest {
assertNull(md.getServiceName());
}
@Test
public void getBareMethodName_extractsMethod() {
Marshaller<Void> marshaller = TestMethodDescriptors.voidMarshaller();
MethodDescriptor<?, ?> md = MethodDescriptor.newBuilder(marshaller, marshaller)
.setType(MethodType.UNARY)
.setFullMethodName("foo/bar")
.build();
assertEquals("bar", md.getBareMethodName());
}
@Test
public void getBareMethodName_returnsNull() {
Marshaller<Void> marshaller = TestMethodDescriptors.voidMarshaller();
MethodDescriptor<?, ?> md = MethodDescriptor.newBuilder(marshaller, marshaller)
.setType(MethodType.UNARY)
.setFullMethodName("foo-bar")
.build();
assertNull(md.getBareMethodName());
}
@Test
public void getBareMethodName_returnsEmptyStringWithMethodMissing() {
Marshaller<Void> marshaller = TestMethodDescriptors.voidMarshaller();
MethodDescriptor<?, ?> md = MethodDescriptor.newBuilder(marshaller, marshaller)
.setType(MethodType.UNARY)
.setFullMethodName("foo/")
.build();
assertTrue(md.getBareMethodName().isEmpty());
}
@Test
public void toBuilderTest() {
MethodDescriptor<String, String> md1 = MethodDescriptor.<String, String>newBuilder()