下面列出了怎么用com.google.protobuf.DescriptorProtos.ServiceDescriptorProto的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public TypeSpec.Builder newServiceClassBuilder(final ServiceDescriptorProto serviceProto) {
final String className = deconflictJavaTypeName(sanitizeClassName(serviceProto.getName()));
final TypeSpec.Builder builder = TypeSpec.classBuilder(className)
.addModifiers(PUBLIC, FINAL)
.addMethod(constructorBuilder()
.addModifiers(PRIVATE)
.addComment("no instances")
.build());
if (deprecated || serviceProto.hasOptions() && serviceProto.getOptions().hasDeprecated() &&
serviceProto.getOptions().getDeprecated()) {
builder.addAnnotation(Deprecated.class);
}
serviceClassBuilders.add(builder);
return builder;
}
void generate(final ServiceDescriptorProto serviceProto) {
final State state = new State(serviceProto);
final TypeSpec.Builder serviceClassBuilder = context.newServiceClassBuilder(serviceProto);
addSerializationProviderInit(state, serviceClassBuilder);
addServiceRpcInterfaces(state, serviceClassBuilder);
addServiceInterfaces(state, serviceClassBuilder);
addServiceFilter(state, serviceClassBuilder);
addServiceFilterFactory(state, serviceClassBuilder);
addServiceFactory(state, serviceClassBuilder);
addClientMetadata(state, serviceClassBuilder);
addClientInterfaces(state, serviceClassBuilder);
addClientFilter(state, serviceClassBuilder);
addClientFilterFactory(state, serviceClassBuilder);
addClientFactory(state, serviceClassBuilder);
}
private ServiceDescriptor(final ServiceDescriptorProto proto,
final FileDescriptor file,
final int index)
throws DescriptorValidationException {
this.index = index;
this.proto = proto;
fullName = computeFullName(file, null, proto.getName());
this.file = file;
methods = new MethodDescriptor[proto.getMethodCount()];
for (int i = 0; i < proto.getMethodCount(); i++) {
methods[i] = new MethodDescriptor(
proto.getMethod(i), file, this, i);
}
file.pool.addSymbol(this);
}
public void decompile(FileDescriptorProto fileDescriptor) throws IOException {
if (fileDescriptor.hasPackage()) {
indentedFormat("package %s;", fileDescriptor.getPackage());
absolutePackage = "." + fileDescriptor.getPackage() + ".";
}
for (String dependency : fileDescriptor.getDependencyList()) {
indentedFormat("import \"%s\";", dependency);
}
if (fileDescriptor.hasOptions()) {
decompileOptions(fileDescriptor.getOptions());
}
decompileMembers(fileDescriptor.getEnumTypeList(),
fileDescriptor.getMessageTypeList(),
Collections.<FieldDescriptorProto>emptyList(),
Collections.<DescriptorProto.ExtensionRange>emptyList(),
fileDescriptor.getExtensionList());
for (ServiceDescriptorProto serviceDescriptor : fileDescriptor.getServiceList()) {
decompile(serviceDescriptor);
}
newline();
flush();
}
protected void decompile(ServiceDescriptorProto serviceDescriptor) throws IOException {
indentedFormat("service %s {", serviceDescriptor.getName());
indent++;
if (serviceDescriptor.hasOptions()) {
decompileOptions(serviceDescriptor.getOptions());
}
for (MethodDescriptorProto methodDescriptor : serviceDescriptor.getMethodList()) {
indentedFormat("rpc %s (%s) returns (%s)",
methodDescriptor.getName(), methodDescriptor.getInputType(), methodDescriptor.getOutputType());
if (methodDescriptor.hasOptions()) {
write("{ ");
indent++;
decompileOptions(methodDescriptor.getOptions());
indent--;
indentedFormat("}");
}
else {
write(";");
}
}
indent--;
indentedFormat("}");
}
@Nullable
private static String getFullName(FileDescriptorProto descriptor, List<Integer> path) {
String fullNameSoFar = descriptor.getPackage();
switch (path.get(0)) {
case FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER:
final DescriptorProto message = descriptor.getMessageType(path.get(1));
return appendMessageToFullName(message, path, fullNameSoFar);
case FileDescriptorProto.ENUM_TYPE_FIELD_NUMBER:
final EnumDescriptorProto enumDescriptor = descriptor.getEnumType(path.get(1));
return appendEnumToFullName(enumDescriptor, path, fullNameSoFar);
case FileDescriptorProto.SERVICE_FIELD_NUMBER:
final ServiceDescriptorProto serviceDescriptor = descriptor.getService(path.get(1));
fullNameSoFar = appendNameComponent(fullNameSoFar, serviceDescriptor.getName());
if (path.size() > 2) {
fullNameSoFar = appendFieldComponent(
fullNameSoFar, serviceDescriptor.getMethod(path.get(3)).getName());
}
return fullNameSoFar;
default:
return null;
}
}
@Override
public String methodPath(final ServiceDescriptorProto serviceProto, final MethodDescriptorProto methodProto) {
final StringBuilder sb = new StringBuilder(128).append('/');
if (isNotNullNorEmpty(protoPackageName)) {
sb.append(protoPackageName).append('.');
}
sb.append(serviceProto.getName()).append('/').append(methodProto.getName());
return sb.toString();
}
private ServiceContext buildServiceContext(ServiceDescriptorProto serviceProto, ProtoTypeMap typeMap, List<Location> locations, int serviceNumber) {
ServiceContext serviceContext = new ServiceContext();
serviceContext.fileName = getClassPrefix() + serviceProto.getName() + "Grpc.java";
serviceContext.className = getClassPrefix() + serviceProto.getName() + "Grpc";
serviceContext.serviceName = serviceProto.getName();
serviceContext.deprecated = serviceProto.getOptions() != null && serviceProto.getOptions().getDeprecated();
List<Location> allLocationsForService = locations.stream()
.filter(location ->
location.getPathCount() >= 2 &&
location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER &&
location.getPath(1) == serviceNumber
)
.collect(Collectors.toList());
Location serviceLocation = allLocationsForService.stream()
.filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS)
.findFirst()
.orElseGet(Location::getDefaultInstance);
serviceContext.javaDoc = getJavaDoc(getComments(serviceLocation), getServiceJavaDocPrefix());
for (int methodNumber = 0; methodNumber < serviceProto.getMethodCount(); methodNumber++) {
MethodContext methodContext = buildMethodContext(
serviceProto.getMethod(methodNumber),
typeMap,
locations,
methodNumber
);
serviceContext.methods.add(methodContext);
}
return serviceContext;
}
private void doPrint(FileDescriptorProto fdp, String javaPackage, String outerClassName) {
List<DescriptorProto> messageDescList = Lists.newArrayList(fdp.getMessageTypeList());
List<ServiceDescriptorProto> serviceDescList = Lists.newArrayList(fdp.getServiceList());
List<EnumDescriptorProto> enumDescList = Lists.newArrayList(fdp.getEnumTypeList());
messageDescList.stream().filter(temp -> temp.getEnumTypeList() != null)
.forEach(temp -> enumDescList.addAll(temp.getEnumTypeList()));
printEnum(enumDescList, javaPackage, outerClassName);
printMessage(messageDescList, javaPackage, outerClassName);
printService(serviceDescList, javaPackage);
}
private void printService(List<ServiceDescriptorProto> serviceDescList, String javaPackage) {
for (ServiceDescriptorProto serviceDesc : serviceDescList) {
PrintServiceFile serviceFile =
new PrintServiceFile(generatePath, javaPackage, serviceDesc.getName());
try {
serviceFile.setServiceMethods(serviceDesc.getMethodList());
serviceFile.setPojoTypeCache(pojoTypes);
} finally {
serviceFile.print();
}
}
}
private ServiceDescriptorProto generateApi(Api api) {
ServiceDescriptorProto.Builder builder = ServiceDescriptorProto.newBuilder();
builder.setName(getSimpleName(api.getName()));
for (Method method : api.getMethodsList()) {
builder.addMethod(generateMethod(method));
}
if (!api.getOptionsList().isEmpty()) {
builder.setOptions(generateServiceOptions(api));
}
return builder.build();
}
private Interface(ProtoFile parent, ServiceDescriptorProto proto, String path) {
super(parent, proto.getName(), path);
this.proto = proto;
// Build methods.
ImmutableList.Builder<Method> methodsBuilder = ImmutableList.builder();
List<MethodDescriptorProto> methodProtos = proto.getMethodList();
for (int i = 0; i < methodProtos.size(); i++) {
String childPath = buildPath(path, ServiceDescriptorProto.METHOD_FIELD_NUMBER, i);
methodsBuilder.add(Method.create(this, methodProtos.get(i), childPath));
}
methods = methodsBuilder.build();
}
@Accepts
protected void accept(ServiceDescriptorProto.Builder service) {
pushParent(BuilderVisitorNodeInfo.create(service, currentFile));
visitRepeated(ServiceDescriptorProto.METHOD_FIELD_NUMBER);
visit(service.getOptionsBuilder());
popExpectedParent(service);
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final ServiceDescriptorProto proto) {
this.proto = proto;
for (int i = 0; i < methods.length; i++) {
methods[i].setProto(proto.getMethod(i));
}
}
List<ServiceDescriptorProto> protoServices() {
return protoFile.getServiceList();
}
private State(final ServiceDescriptorProto serviceProto) {
this.serviceProto = serviceProto;
}
private static String serviceFactoryBuilderInitChain(final ServiceDescriptorProto serviceProto,
final boolean blocking) {
return serviceProto.getMethodList().stream()
.map(methodProto -> routeName(methodProto) + (blocking ? Blocking : "") + '(' + service + ')')
.collect(joining("."));
}
public static List<Option> getOptions(ServiceDescriptorProto descriptor) {
return getOptions(descriptor, true);
}
public static List<Option> getOptions(ServiceDescriptorProto descriptor, boolean withDefaults) {
return toCoreOptions(maybeCombineOptionsWithDefault(withDefaults,
descriptor.getOptions().getAllFields(), DEFAULT_SERVICE_OPTIONS));
}
/**
* Creates a interface backed up by the given proto.
*/
public static Interface create(ProtoFile parent, ServiceDescriptorProto proto, String path) {
return new Interface(parent, proto, path);
}
/**
* Returns the underlying proto representation.
*/
public ServiceDescriptorProto getProto() {
return proto;
}
private void restify(MethodKind httpKind, String simpleName, String template) {
Model model = Model.create(FileDescriptorSet.getDefaultInstance());
model.setServiceConfig(
ConfigSource.newBuilder(Service.getDefaultInstance())
.setValue(
Service.getDescriptor().findFieldByNumber(Service.CONFIG_VERSION_FIELD_NUMBER),
null,
UInt32Value.newBuilder().setValue(configVersion).build(),
new SimpleLocation("from test"))
.build());
HttpConfigAspect aspect = HttpConfigAspect.create(model);
ProtoFile file =
ProtoFile.create(
model, FileDescriptorProto.getDefaultInstance(), true, ExtensionPool.EMPTY);
Interface iface = Interface.create(file, ServiceDescriptorProto.getDefaultInstance(), "");
Method method =
Method.create(iface, MethodDescriptorProto.newBuilder().setName(simpleName).build(), "");
RestMethod restMethod;
ImmutableList<PathSegment> path = parse(model, template);
if (!model.getDiagReporter().getDiagCollector().getDiags().isEmpty()) {
restMethod = RestMethod.create(method, RestKind.CUSTOM, "*error*", "*error*", null);
} else {
HttpRule httpRule = HttpRule.getDefaultInstance();
HttpAttribute httpConfig =
new HttpAttribute(
httpRule,
httpKind,
MessageType.create(file, Empty.getDescriptor().toProto(), "", ExtensionPool.EMPTY),
path,
"",
false,
ImmutableList.<HttpAttribute>of(),
false);
RestAnalyzer analyzer = new RestAnalyzer(aspect);
restMethod = analyzer.analyzeMethod(method, httpConfig);
}
PrintWriter pw = testOutput();
pw.print(httpKind.toString());
pw.print(" ");
pw.print(simpleName);
pw.print(" ");
pw.print(template.isEmpty() ? "(empty)" : template);
pw.println();
pw.println(Strings.repeat("=", 70));
pw.printf("Rest Kind: %s\n", restMethod.getRestKind());
pw.printf(
"Version: %s\n", restMethod.getVersion().isEmpty() ? "(empty)" : restMethod.getVersion());
pw.printf(
"Version with default: %s\n",
restMethod.getVersionWithDefault().isEmpty()
? "(empty)"
: restMethod.getVersionWithDefault());
pw.printf(
"Simple collection: %s\n",
restMethod.getRestCollectionName().isEmpty()
? "(empty)"
: restMethod.getSimpleRestCollectionName());
pw.printf(
"Versioned collection: %s\n",
restMethod.getRestCollectionName().isEmpty()
? "(empty)" : restMethod.getRestCollectionName());
pw.printf("Base collection: %s\n",
restMethod.getBaseRestCollectionName().isEmpty()
? "(empty)" : restMethod.getBaseRestCollectionName());
pw.printf("Custom Name: %s\n",
restMethod.getRestKind() == RestKind.CUSTOM
? restMethod.getRestMethodName() : "(null)");
List<Diag> diags = model.getDiagReporter().getDiagCollector().getDiags();
if (diags.size() > 0) {
pw.println("Diagnostics:");
for (Diag d : diags) {
pw.printf(" %s\n", DiagUtils.getDiagToPrint(d, true));
}
}
pw.println();
}
/** Convert the descriptor to its protocol message representation. */
@Override
public ServiceDescriptorProto toProto() {
return proto;
}
TypeSpec.Builder newServiceClassBuilder(ServiceDescriptorProto serviceProto);
String methodPath(ServiceDescriptorProto serviceProto, MethodDescriptorProto methodProto);