GqlInputConverter build() { HashBiMap<String, Descriptor> mapping = HashBiMap.create(); HashBiMap<String, EnumDescriptor> enumMapping = HashBiMap.create(getEnumMap(enumDescriptors)); LinkedList<Descriptor> loop = new LinkedList<>(descriptors); Set<FileDescriptor> fileDescriptorSet = ProtoRegistry.extractDependencies(fileDescriptors); for (FileDescriptor fileDescriptor : fileDescriptorSet) { loop.addAll(fileDescriptor.getMessageTypes()); enumMapping.putAll(getEnumMap(fileDescriptor.getEnumTypes())); } while (!loop.isEmpty()) { Descriptor descriptor = loop.pop(); if (!mapping.containsKey(descriptor.getFullName())) { mapping.put(getReferenceName(descriptor), descriptor); loop.addAll(descriptor.getNestedTypes()); enumMapping.putAll(getEnumMap(descriptor.getEnumTypes())); } } return new GqlInputConverter( ImmutableBiMap.copyOf(mapping), ImmutableBiMap.copyOf(enumMapping)); }
static Set<FileDescriptor> extractDependencies(List<FileDescriptor> fileDescriptors) { LinkedList<FileDescriptor> loop = new LinkedList<>(fileDescriptors); HashSet<FileDescriptor> fileDescriptorSet = new HashSet<>(fileDescriptors); while (!loop.isEmpty()) { FileDescriptor fileDescriptor = loop.pop(); for (FileDescriptor dependency : fileDescriptor.getDependencies()) { if (!fileDescriptorSet.contains(dependency)) { fileDescriptorSet.add(dependency); loop.push(dependency); } } } return ImmutableSet.copyOf(fileDescriptorSet); }
private EnumValueDescriptor parseEnum(EnumDescriptor enumDescriptor, JsonElement json) throws InvalidProtocolBufferException { String value = json.getAsString(); EnumValueDescriptor result = enumDescriptor.findValueByName(value); if (result == null) { // Try to interpret the value as a number. try { int numericValue = parseInt32(json); if (enumDescriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3) { result = enumDescriptor.findValueByNumberCreatingIfUnknown(numericValue); } else { result = enumDescriptor.findValueByNumber(numericValue); } } catch (InvalidProtocolBufferException e) { // Fall through. This exception is about invalid int32 value we get from parseInt32() but // that's not the exception we want the user to see. Since result == null, we will throw // an exception later. } if (result == null) { throw new InvalidProtocolBufferException( "Invalid enum value: " + value + " for enum type: " + enumDescriptor.getFullName()); } } return result; }
/** Creates a resolver which searches the supplied {@link FileDescriptorSet}. */ public static ServiceResolver fromFileDescriptorSet(FileDescriptorSet descriptorSet) { ImmutableMap<String, FileDescriptorProto> descriptorProtoIndex = computeDescriptorProtoIndex(descriptorSet); Map<String, FileDescriptor> descriptorCache = new HashMap<>(); ImmutableList.Builder<FileDescriptor> result = ImmutableList.builder(); for (FileDescriptorProto descriptorProto : descriptorSet.getFileList()) { try { result.add(descriptorFromProto(descriptorProto, descriptorProtoIndex, descriptorCache)); } catch (DescriptorValidationException e) { logger.warn("Skipped descriptor " + descriptorProto.getName() + " due to error", e); continue; } } return new ServiceResolver(result.build()); }
/** * Recursively constructs file descriptors for all dependencies of the supplied proto and returns * a {@link FileDescriptor} for the supplied proto itself. For maximal efficiency, reuse the * descriptorCache argument across calls. */ private static FileDescriptor descriptorFromProto( FileDescriptorProto descriptorProto, ImmutableMap<String, FileDescriptorProto> descriptorProtoIndex, Map<String, FileDescriptor> descriptorCache) throws DescriptorValidationException { // First, check the cache. String descritorName = descriptorProto.getName(); if (descriptorCache.containsKey(descritorName)) { return descriptorCache.get(descritorName); } // Then, fetch all the required dependencies recursively. ImmutableList.Builder<FileDescriptor> dependencies = ImmutableList.builder(); for (String dependencyName : descriptorProto.getDependencyList()) { if (!descriptorProtoIndex.containsKey(dependencyName)) { throw new IllegalArgumentException("Could not find dependency: " + dependencyName); } FileDescriptorProto dependencyProto = descriptorProtoIndex.get(dependencyName); dependencies.add(descriptorFromProto(dependencyProto, descriptorProtoIndex, descriptorCache)); } // Finally, construct the actual descriptor. FileDescriptor[] empty = new FileDescriptor[0]; return FileDescriptor.buildFrom(descriptorProto, dependencies.build().toArray(empty)); }
public void registerGpbMsgDesc(FileDescriptor fileDescriptor) { if (fileDescriptor == null) return; // service for (ServiceDescriptor service : fileDescriptor.getServices()) { for (MethodDescriptor method : service.getMethods()) { if (gpbMsgDescMap.containsKey(method.getName())) { LOG.error("[Gpb] the method [" + method.getName() + "] already registered."); } registerGpbMessage(method.getInputType()); methodInputTypeMap.put(method.getName(), method.getInputType().getName()); } } // message for (Descriptor descriptor : fileDescriptor.getMessageTypes()) { registerGpbMessage(descriptor); } }
private void loadService() { LOG.info("Load service definition is starting..."); InputStream in = null; FileDescriptorSet descriptorSet; try { in = ClassHelper.getClassLoader().getResourceAsStream(GrpcConstants.PROTO_DESC_FILENAME); descriptorSet = FileDescriptorSet.parseFrom(in); for (FileDescriptorProto fdp : descriptorSet.getFileList()) { FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {}, true); for (com.google.protobuf.Descriptors.ServiceDescriptor service : fd.getServices()) { addServiceDenifition(service.getName(), fd.getOptions().getJavaPackage() + '.' + service.getFullName()); } } LOG.info("Load service denifition is finished, total {} service are found.", services.size()); } catch (Exception ex) { LOG.error("Load service denifition error happened.", ex); throw new RuntimeException(ex); } finally { IOUtils.closeInputStream(in); } }
public static ProtobufRowDataConverter forGroup(Group group, FileDescriptor fileDescriptor) { // Find the group message. Descriptor groupMessage = null; List<Descriptor> messages = fileDescriptor.getMessageTypes(); for (int i = messages.size() - 1; i >= 0; i--) { Descriptor message = messages.get(i); if (message.getOptions().getExtension(TableOptions.fdbsql).getIsGroup()) { groupMessage = message; break; } } if (groupMessage != null) { return new GroupConverter(group, groupMessage); } else { assert (messages.size() == 1 && group.getRoot().getChildJoins().isEmpty()); return new TableConverter(group.getRoot(), messages.get(0)); } }
public static ProtobufRowConverter forGroup(Group group, FileDescriptor fileDescriptor) { // Find the group message. Descriptor groupMessage = null; List<Descriptor> messages = fileDescriptor.getMessageTypes(); for (int i = messages.size() - 1; i >= 0; i--) { Descriptor message = messages.get(i); if (message.getOptions().getExtension(TableOptions.fdbsql).getIsGroup()) { groupMessage = message; break; } } if (groupMessage != null) { return new GroupConverter(group, groupMessage); } else { assert (messages.size() == 1 && group.getRoot().getChildJoins().isEmpty()); return new TableConverter(group.getRoot(), messages.get(0)); } }
public void testDependencyOrder() throws Exception { FileDescriptorProto fooProto = FileDescriptorProto.newBuilder() .setName("foo.proto").build(); FileDescriptorProto barProto = FileDescriptorProto.newBuilder() .setName("bar.proto") .addDependency("foo.proto") .build(); FileDescriptorProto bazProto = FileDescriptorProto.newBuilder() .setName("baz.proto") .addDependency("foo.proto") .addDependency("bar.proto") .addPublicDependency(0) .addPublicDependency(1) .build(); FileDescriptor fooFile = Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0]); FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(barProto, new FileDescriptor[] {fooFile}); // Items in the FileDescriptor array can be in any order. Descriptors.FileDescriptor.buildFrom(bazProto, new FileDescriptor[] {fooFile, barFile}); Descriptors.FileDescriptor.buildFrom(bazProto, new FileDescriptor[] {barFile, fooFile}); }
public void testInvalidPublicDependency() throws Exception { FileDescriptorProto fooProto = FileDescriptorProto.newBuilder() .setName("foo.proto").build(); FileDescriptorProto barProto = FileDescriptorProto.newBuilder() .setName("boo.proto") .addDependency("foo.proto") .addPublicDependency(1) // Error, should be 0. .build(); FileDescriptor fooFile = Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0]); try { Descriptors.FileDescriptor.buildFrom(barProto, new FileDescriptor[] {fooFile}); fail("DescriptorValidationException expected"); } catch (DescriptorValidationException e) { assertTrue( e.getMessage().indexOf("Invalid public dependency index.") != -1); } }
public void testPackedEnumField() throws Exception { FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder() .setName("foo.proto") .addEnumType(EnumDescriptorProto.newBuilder() .setName("Enum") .addValue(EnumValueDescriptorProto.newBuilder() .setName("FOO") .setNumber(1) .build()) .build()) .addMessageType(DescriptorProto.newBuilder() .setName("Message") .addField(FieldDescriptorProto.newBuilder() .setName("foo") .setTypeName("Enum") .setNumber(1) .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) .setOptions(DescriptorProtos.FieldOptions.newBuilder() .setPacked(true) .build()) .build()) .build()) .build(); Descriptors.FileDescriptor.buildFrom( fileDescriptorProto, new FileDescriptor[0]); }
private FileDescriptorProto makeCanonicalProto(final FileDescriptor fileDescriptor) { final FileDescriptorProto.Builder protoBuilder = FileDescriptorProto.newBuilder(fileDescriptor.toProto()); for (final FieldDescriptorProto.Builder field : protoBuilder.getExtensionBuilderList()) { makeCanonicalField(field, fileDescriptor.findExtensionByName(field.getName())); } for (final DescriptorProto.Builder message : protoBuilder.getMessageTypeBuilderList()) { makeCanonicalMessage(message, fileDescriptor.findMessageTypeByName(message.getName())); } // for (EnumDescriptorProto.Builder enumProto : // protoBuilder.getEnumTypeBuilderList()) { // makeCanonicalEnum(enumProto, // fileDescriptor.findEnumTypeByName(enumProto.getName())); // } for (final ServiceDescriptorProto.Builder serviceProto : protoBuilder.getServiceBuilderList()) { makeCanonicalService(serviceProto, fileDescriptor.findServiceByName(serviceProto.getName())); } // TODO: incorporate options' tree walking into canonicalization to eliminate double walking return OptionResolver.newBuilder().setCustomOptionsAsExtensions(false) .resolveAllOptionsFor(fileDescriptor, protoBuilder).build(); }
public boolean resolveAllRefs(final Collection<FileDescriptor> dependencies, final IProtoErrorListener errorListener) { if (isBuilt()) { throw new IllegalStateException("not supported when proto is already built"); } final Map<String, NameContext> cache = new HashMap<String, NameContext>(); if (resolveAllRefs(dependencies, errorListener, cache)) { return true; } for (final Entry<FieldDescriptorProto.Builder, FieldContext> entry : unresolved) { reportUnresolvedTypeNameError(entry.getKey(), entry.getValue(), errorListener); } return false; }
private boolean buildAndCacheProto(final Map<String, FileDescriptor> cache, final ParsedContext fileProto, final FileDescriptor[] dependencies, final IBaseProtoErrorListener errorListener) { try { // if (fileProto.resolveAllRefs(Arrays.asList(dependencies), errorListener)) { // TODO: implement ProtoFileParser.hasCustomOption(); then skip build's proto // reserialization and OptionResolver if hasCustomOption() is true! final FileDescriptor fileDescriptor = fileBuilder.setProto(fileProto.getProto()).addDependencies(dependencies).build(); cache.put(fileProto.getProto().getName(), fileDescriptor); return true; // } } catch (final DescriptorValidationRuntimeException e) { errorListener.setProtoName(fileProto.getProto().getName()); errorListener.validationError(null, null, e.getDescription(), e); } return false; }
private FileDescriptor getDeepCanonicalFileDescriptor(final FileDescriptor file, final boolean forceRebuild) throws DescriptorValidationException { if (!forceRebuild && isDeeplyCanonical(file)) { return file; } final FileDescriptor[] dependencies = new FileDescriptor[file.getDependencies().size()]; int i = 0; for (final FileDescriptor dependency : file.getDependencies()) { dependencies[i++] = getDeepCanonicalFileDescriptor(dependency, forceRebuild); } final FileDescriptorProto proto = isCanonical(file) ? file.toProto() : makeCanonicalProto(file); return buildFileDescriptorWithReserializedProto(proto, dependencies); }
private FileDescriptorProto makeCanonicalProto(final FileDescriptor file) { final FileDescriptorProto.Builder protoBuilder = FileDescriptorProto.newBuilder(file.toProto()); for (final FieldDescriptorProto.Builder field : protoBuilder.getExtensionBuilderList()) { makeCanonicalField(field, file.findExtensionByName(field.getName())); } for (final DescriptorProto.Builder message : protoBuilder.getMessageTypeBuilderList()) { makeCanonicalMessage(message, file.findMessageTypeByName(message.getName())); } // for (EnumDescriptorProto.Builder enumProto : // protoBuilder.getEnumTypeBuilderList()) { // makeCanonicalEnum(enumProto, // file.findEnumTypeByName(enumProto.getName())); // } for (final ServiceDescriptorProto.Builder serviceProto : protoBuilder.getServiceBuilderList()) { makeCanonicalService(serviceProto, file.findServiceByName(serviceProto.getName())); } return OptionResolver.newBuilder().setCustomOptionsAsExtensions(reparseCustomOptions) .resolveAllOptionsFor(file, protoBuilder).build(); }
@Test public void testUnresolvedNamesPostBuildFileProto() throws Exception { final FileDescriptorProto child1 = getProtocFileDescriptorProto("nonTreeChild1.proto", false, FieldTypeRefsMode.AS_IS); final FileDescriptorProto child2 = getProtocFileDescriptorProto("nonTreeChild2.proto", false, FieldTypeRefsMode.AS_IS); final FileDescriptorProto originalParent1 = getProtocFileDescriptorProto("nonTreeParent1.proto", false, FieldTypeRefsMode.AS_IS); final FileDescriptorProto parent2 = getProtocFileDescriptorProto("nonTreeParent2.proto", false, FieldTypeRefsMode.AS_IS); final Builder parentBuilder = FileDescriptorProto.newBuilder(originalParent1); parentBuilder.getMessageTypeBuilder(0).getFieldBuilder(2).clearType().setTypeName("Child2"); final FileDescriptorProto parent1 = parentBuilder.build(); final FileDescriptor fileChild2 = FileDescriptor.buildFrom(child2, new FileDescriptor[0]); final FileDescriptor fileParent2 = FileDescriptor.buildFrom(parent2, new FileDescriptor[] {fileChild2}); final FileDescriptor fileChild1 = FileDescriptor.buildFrom(child1, new FileDescriptor[] {fileParent2}); final FileDescriptor fileParent1 = FileDescriptor.buildFrom(parent1, new FileDescriptor[] {fileChild1}); log.info(fileParent1.toProto().toString()); }
@Test public void testUnresolvedNamesAllPostBuildFileProto() throws Exception { final FileDescriptorProto child1 = getProtocFileDescriptorProto("nonTreeChild1.proto", false, RELATIVE_TO_PARENT); final FileDescriptorProto child2 = getProtocFileDescriptorProto("nonTreeChild2.proto", false, RELATIVE_TO_PARENT); final FileDescriptorProto parent1 = getProtocFileDescriptorProto("nonTreeParent1.proto", false, RELATIVE_TO_PARENT); final FileDescriptorProto parent2 = getProtocFileDescriptorProto("nonTreeParent2.proto", false, RELATIVE_TO_PARENT); final FileDescriptor fileChild2 = FileDescriptor.buildFrom(child2, new FileDescriptor[0]); final FileDescriptor fileParent2 = FileDescriptor.buildFrom(parent2, new FileDescriptor[] {fileChild2}); final FileDescriptor fileChild1 = FileDescriptor.buildFrom(child1, new FileDescriptor[] {fileParent2}); final FileDescriptor fileParent1 = FileDescriptor.buildFrom(parent1, new FileDescriptor[] {fileChild1}); log.info(fileParent1.toProto().toString()); }
@Test public void testInvalidExtensionRange1() throws Exception { // given baseDir = new File(baseDir, "NonUniqueExtensionName1"); final File errorsFile = new File(baseDir, "errors.txt"); assertThat("cannot read file", errorsFile.canRead()); final String expectedErrorText = Files.asCharSource(errorsFile, Charsets.UTF_8).read(); // when final Map<String, FileDescriptor> result = filesBuilder.addFilesByRegex(baseDir, filePattern).build(); // then final ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); // TODO: add position capturing and asserts! verify(mockErrorListener, atLeastOnce()).validationError(anyInt(), anyInt(), argument.capture(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); // verify(mockErrorListener, atLeast(protocFdProtos.size())).setProtoName(anyString()); final List<String> actualErrors = argument.getAllValues(); assertThat(result, is(nullValue())); assertThat(expectedErrorText, stringContainsInOrder(actualErrors)); }
@Test public void testTextFormatWithDescriptor() throws Exception { //TestUtil.getAllSet(); String allSet = TextFormat.printToString(TestUtil.getAllSet()); final DescriptorProto expectedAllSetProto = TestAllTypes.getDescriptor().toProto(); String allSetProto = TextFormat.printToString(expectedAllSetProto); log.debug("the message: {}", allSet); log.debug("the proto: {}", allSetProto); DynamicMessage.Builder builder = DynamicMessage.newBuilder(DescriptorProto.getDescriptor()); TextFormat.merge(allSetProto, builder); Message actualAllSetProto = builder.build(); assertThat(actualAllSetProto).isEqualTo(expectedAllSetProto); FieldDescriptor field = FileDescriptorProto.getDescriptor() .findFieldByNumber(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER); FileDescriptorProto fileProto = FileDescriptorProto.newBuilder().setName("my file1") .addRepeatedField(field, actualAllSetProto) .build(); FileDescriptor fileDescriptor = FileDescriptor.buildFrom(fileProto, new FileDescriptor[0]); Descriptor actualAllTypesDescriptor = fileDescriptor.findMessageTypeByName( TestAllTypes.getDescriptor().getFullName()); assertThat(actualAllTypesDescriptor, equalTo(TestAllTypes.getDescriptor())); }
private FileDescriptorSet.Builder addDescriptorToFileSet(FileDescriptorSet.Builder builder, Descriptor descriptor, Set<FileDescriptorProto> fileProtoSet) { List<? extends FileDescriptorProtoOrBuilder> fileList = builder.getFileOrBuilderList(); final FileDescriptor file = descriptor.getFile(); FileDescriptorProto proto = file.toProto(); if (fileList.contains(proto)) { return builder; } builder.addFile(proto); for (FileDescriptor dependency : file.getDependencies()) { proto = dependency.toProto(); if (!fileList.contains(proto)) { builder.addFile(proto); } } return builder; }
/** * protoc custom options' UnknownFieldSet serialization is different from Java; the resulted * extensions are the same, but UnknownFieldSets are different, thus the invariant has been * violated. When the serializations become identical, the test will start failing, indicating * everything is alright, so the expected exception will have to be safely removed! */ @Test public void unknownToExtensionsToUnknownShouldBeEqualProtoc() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(false).setProtocCompatible(false) .addProtos(protocFdProtos).build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); expected.expect(Throwable.class); for (final FileDescriptor file : files) { assertReserializationInvariant(file); } }
@Test public void extensionsToUnknownToExtensionsShouldBeEqualProtoc() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(true).setProtocCompatible(false) .addProtos(protocFdProtos).build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); for (final FileDescriptor file : files) { assertReserializationInvariant2(file); } }
@Test public void extensionsToUnknownToExtensionsShouldBeEqual() throws URISyntaxException, IOException { // when final Collection<FileDescriptor> files = filesBuilder.setCustomOptionsAsExtensions(true).setProtocCompatible(false) .addFilesByGlob(baseDir, "**/*.proto").build(false).values(); // then // no errors logged! verify(mockErrorListener, never()).validationError(anyInt(), anyInt(), anyString(), any(RuntimeException.class)); verify(mockErrorListener, never()).syntaxError(any(Recognizer.class), any(), anyInt(), anyInt(), anyString(), any(RecognitionException.class)); for (final FileDescriptor file : files) { assertReserializationInvariant2(file); } }
private static String getClassName( String nameWithoutPackage, FileDescriptor file, ProtoFlavor flavor) { StringBuilder sb = new StringBuilder(); if (multipleJavaFiles(file, flavor)) { sb.append(getPackage(file, flavor)); if (sb.length() > 0) { sb.append('.'); } } else { sb.append(getClassName(file, flavor)); if (sb.length() > 0) { sb.append('$'); } } sb.append(nameWithoutPackage.replace('.', '$')); return sb.toString(); }
private static FileDescriptor buildDescriptor( String name, Map<String, FileDescriptor> descriptors, Map<String, FileDescriptorProto> protos) throws DescriptorValidationException { FileDescriptor file = descriptors.get(name); if (file != null) { return file; } FileDescriptorProto proto = protos.get(name); FileDescriptor[] deps = new FileDescriptor[proto.getDependencyCount()]; for (int i = 0; i < proto.getDependencyCount(); i++) { deps[i] = buildDescriptor(proto.getDependency(i), descriptors, protos); } file = FileDescriptor.buildFrom(proto, deps); descriptors.put(name, file); return file; }
public void testInvalidPublicDependency() throws Exception { FileDescriptorProto fooProto = FileDescriptorProto.newBuilder() .setName("foo.proto") .build(); FileDescriptorProto barProto = FileDescriptorProto.newBuilder() .setName("boo.proto") .addDependency("foo.proto") .addPublicDependency(1) // Error, should be 0. .build(); FileDescriptor fooFile = Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0]); try { Descriptors.FileDescriptor.buildFrom(barProto, new FileDescriptor[] {fooFile}); fail("DescriptorValidationException expected"); } catch (DescriptorValidationException e) { assertTrue( e.getMessage().indexOf("Invalid public dependency index.") != -1); } }
private ServerReflectionResponse createServerReflectionResponse( ServerReflectionRequest request, FileDescriptor fd) { FileDescriptorResponse.Builder fdRBuilder = FileDescriptorResponse.newBuilder(); Set<String> seenFiles = new HashSet<String>(); Queue<FileDescriptor> frontier = new ArrayDeque<FileDescriptor>(); seenFiles.add(fd.getName()); frontier.add(fd); while (!frontier.isEmpty()) { FileDescriptor nextFd = frontier.remove(); fdRBuilder.addFileDescriptorProto(nextFd.toProto().toByteString()); for (FileDescriptor dependencyFd : nextFd.getDependencies()) { if (!seenFiles.contains(dependencyFd.getName())) { seenFiles.add(dependencyFd.getName()); frontier.add(dependencyFd); } } } return ServerReflectionResponse.newBuilder() .setValidHost(request.getHost()) .setOriginalRequest(request) .setFileDescriptorResponse(fdRBuilder) .build(); }
private void processService(ServiceDescriptor service, FileDescriptor fd) { String serviceName = service.getFullName(); checkState( !fileDescriptorsBySymbol.containsKey(serviceName), "Service already defined: %s", serviceName); fileDescriptorsBySymbol.put(serviceName, fd); for (MethodDescriptor method : service.getMethods()) { String methodName = method.getFullName(); checkState( !fileDescriptorsBySymbol.containsKey(methodName), "Method already defined: %s", methodName); fileDescriptorsBySymbol.put(methodName, fd); } }
/** * Tests that the DescriptorValidationException works as intended. */ public void testDescriptorValidatorException() throws Exception { FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder() .setName("foo.proto") .addMessageType(DescriptorProto.newBuilder() .setName("Foo") .addField(FieldDescriptorProto.newBuilder() .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) .setType(FieldDescriptorProto.Type.TYPE_INT32) .setName("foo") .setNumber(1) .setDefaultValue("invalid") .build()) .build()) .build(); try { Descriptors.FileDescriptor.buildFrom(fileDescriptorProto, new FileDescriptor[0]); fail("DescriptorValidationException expected"); } catch (DescriptorValidationException e) { // Expected; check that the error message contains some useful hints assertTrue(e.getMessage().indexOf("foo") != -1); assertTrue(e.getMessage().indexOf("Foo") != -1); assertTrue(e.getMessage().indexOf("invalid") != -1); assertTrue(e.getCause() instanceof NumberFormatException); assertTrue(e.getCause().getMessage().indexOf("invalid") != -1); } }
private static BiMap<String, GraphQLType> getMap( List<FileDescriptor> fileDescriptors, List<Descriptor> descriptors, List<EnumDescriptor> enumDescriptors, GraphQLInterfaceType nodeInterface) { HashBiMap<String, GraphQLType> mapping = HashBiMap.create(getEnumMap(enumDescriptors)); LinkedList<Descriptor> loop = new LinkedList<>(descriptors); Set<FileDescriptor> fileDescriptorSet = extractDependencies(fileDescriptors); for (FileDescriptor fileDescriptor : fileDescriptorSet) { loop.addAll(fileDescriptor.getMessageTypes()); mapping.putAll(getEnumMap(fileDescriptor.getEnumTypes())); } while (!loop.isEmpty()) { Descriptor descriptor = loop.pop(); if (!mapping.containsKey(descriptor.getFullName())) { mapping.put( ProtoToGql.getReferenceName(descriptor), ProtoToGql.convert(descriptor, nodeInterface)); GqlInputConverter inputConverter = GqlInputConverter.newBuilder().add(descriptor.getFile()).build(); mapping.put( GqlInputConverter.getReferenceName(descriptor), inputConverter.getInputType(descriptor)); loop.addAll(descriptor.getNestedTypes()); mapping.putAll(getEnumMap(descriptor.getEnumTypes())); } } return ImmutableBiMap.copyOf(mapping); }
@Inject public SchemaImpl( @Annotations.Queries Set<GraphQLFieldDefinition> queryFields, @Annotations.Mutations Set<GraphQLFieldDefinition> mutationFields, @Annotations.GraphModifications Set<TypeModification> modifications, @Annotations.ExtraTypes Set<FileDescriptor> fileDescriptors, @Annotations.Queries Set<NodeDataFetcher> nodeDataFetchers) { this.queryFields = queryFields; this.mutationFields = mutationFields; this.modifications = modifications; this.fileDescriptors = fileDescriptors; this.nodeDataFetchers = nodeDataFetchers; }