类com.google.protobuf.ExtensionRegistry源码实例Demo

下面列出了怎么用com.google.protobuf.ExtensionRegistry的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: metastore   文件: Convert.java
static Map<String, Descriptors.FileDescriptor> registerOptions(
    Map<String, Descriptors.FileDescriptor> fileDescriptorMap) {
  Map<String, DescriptorProtos.FileDescriptorProto> inMap = new HashMap<>();
  Map<String, Descriptors.FileDescriptor> outMap = new HashMap<>();

  fileDescriptorMap.forEach((name, fd) -> inMap.put(name, fd.toProto()));

  ExtensionRegistry registry = ExtensionRegistry.newInstance();
  inMap
      .keySet()
      .forEach(fileName -> convertToFileDescriptorMap(fileName, null, inMap, outMap, registry));

  outMap.forEach(
      (k, fileDescriptor) ->
          Descriptors.FileDescriptor.internalUpdateFileDescriptor(fileDescriptor, registry));
  return outMap;
}
 
源代码2 项目: jigsaw-payment   文件: JsonFormat.java
/**
 * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
 * Extensions will be recognized if they are registered in {@code extensionRegistry}.
 */
public void merge(CharSequence input,
                         ExtensionRegistry extensionRegistry,
                         Message.Builder builder) throws ParseException {
    Tokenizer tokenizer = new Tokenizer(input);

    // Based on the state machine @ http://json.org/

    tokenizer.consume("{"); // Needs to happen when the object starts.
    while (!tokenizer.tryConsume("}")) { // Continue till the object is done
        mergeField(tokenizer, extensionRegistry, builder);
    }
    // Test to make sure the tokenizer has reached the end of the stream.
    if (!tokenizer.atEnd()) {
        throw tokenizer.parseException("Expecting the end of the stream, but there seems to be more data!  Check the input for a valid JSON format.");
    }
}
 
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
		ExtensionRegistry extensionRegistry, Message.Builder builder)
		throws IOException, HttpMessageConversionException {

	if (contentType.isCompatibleWith(APPLICATION_JSON)) {
		this.jsonFormatter.merge(input, charset, extensionRegistry, builder);
	}
	else if (contentType.isCompatibleWith(APPLICATION_XML)) {
		this.xmlFormatter.merge(input, charset, extensionRegistry, builder);
	}
	else {
		throw new HttpMessageConversionException(
				"protobuf-java-format does not support parsing " + contentType);
	}
}
 
源代码4 项目: jigsaw-payment   文件: JsonJacksonFormat.java
/**
 * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
 * Extensions will be recognized if they are registered in {@code extensionRegistry}.
 * @throws IOException
 */
public void merge(JsonParser parser,
						 ExtensionRegistry extensionRegistry,
                         Message.Builder builder) throws IOException {

    JsonToken token = parser.nextToken();
    if (token.equals(JsonToken.START_OBJECT)) {
    	token = parser.nextToken();
    }
    while (token != null && !token.equals(JsonToken.END_OBJECT)) {
    	mergeField(parser, extensionRegistry, builder);
    	token = parser.nextToken();
    }

    // Test to make sure the tokenizer has reached the end of the stream.
    if (parser.nextToken() != null) {
        throw new RuntimeException("Expecting the end of the stream, but there seems to be more data!  Check the input for a valid JSON format.");
    }
}
 
源代码5 项目: datacollector   文件: ProtobufDataParser.java
public ProtobufDataParser(
    ProtoConfigurableEntity.Context context,
    String messageId,
    Descriptors.Descriptor descriptor,
    Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap,
    ExtensionRegistry extensionRegistry,
    InputStream inputStream,
    String readerOffset,
    int maxObjectLength,
    boolean isDelimited
) throws IOException, Descriptors.DescriptorValidationException, DataParserException {
  this.context = context;
  this.inputStream = new OverrunInputStream(inputStream, maxObjectLength, true);
  this.messageId = messageId;
  this.messageTypeToExtensionMap = messageTypeToExtensionMap;
  this.extensionRegistry = extensionRegistry;
  this.descriptor = descriptor;
  this.builder = DynamicMessage.newBuilder(descriptor);
  this.isDelimited = isDelimited;

  // skip to the required location
  if (readerOffset != null && !readerOffset.isEmpty() && !readerOffset.equals("0")) {
    int offset = Integer.parseInt(readerOffset);
    this.inputStream.skip(offset);
  }
}
 
public static ExtensionRegistry getInstance() {
  ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
  Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
      AllExtensions.getDescriptor().getExtensions(),
      RepeatedExtensions.getDescriptor().getExtensions()
  );

  for (FieldDescriptor extension : extensionDescriptors) {
    if (extension.getJavaType() == JavaType.MESSAGE) {
      extensionRegistry.add(extension, Nested.getDefaultInstance());
    } else {
      extensionRegistry.add(extension);
    }
  }

  return extensionRegistry;
}
 
源代码7 项目: jigsaw-payment   文件: JsonJacksonFormat.java
private void handleValue(JsonParser parser,
                                ExtensionRegistry extensionRegistry,
                                Message.Builder builder,
                                FieldDescriptor field,
                                ExtensionRegistry.ExtensionInfo extension,
                                boolean unknown) throws IOException {

    Object value = null;
    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        value = handleObject(parser, extensionRegistry, builder, field, extension, unknown);
    } else {
        value = handlePrimitive(parser, field);
    }
    if (value != null) {
        if (field.isRepeated()) {
            builder.addRepeatedField(field, value);
        } else {
            builder.setField(field, value);
        }
    }
}
 
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
		ExtensionRegistry extensionRegistry, Message.Builder builder)
		throws IOException, HttpMessageConversionException {

	if (contentType.isCompatibleWith(APPLICATION_JSON)) {
		this.jsonFormatter.merge(input, charset, extensionRegistry, builder);
	}
	else if (contentType.isCompatibleWith(APPLICATION_XML)) {
		this.xmlFormatter.merge(input, charset, extensionRegistry, builder);
	}
	else {
		throw new HttpMessageConversionException(
				"protobuf-java-format does not support parsing " + contentType);
	}
}
 
@Test
public void encoderDecoderOverrides() {
	Jackson2JsonDecoder jacksonDecoder = new Jackson2JsonDecoder();
	Jackson2JsonEncoder jacksonEncoder = new Jackson2JsonEncoder();
	ProtobufDecoder protobufDecoder = new ProtobufDecoder(ExtensionRegistry.newInstance());
	ProtobufEncoder protobufEncoder = new ProtobufEncoder();
	Jaxb2XmlEncoder jaxb2Encoder = new Jaxb2XmlEncoder();
	Jaxb2XmlDecoder jaxb2Decoder = new Jaxb2XmlDecoder();

	this.configurer.defaultCodecs().jackson2JsonDecoder(jacksonDecoder);
	this.configurer.defaultCodecs().jackson2JsonEncoder(jacksonEncoder);
	this.configurer.defaultCodecs().protobufDecoder(protobufDecoder);
	this.configurer.defaultCodecs().protobufEncoder(protobufEncoder);
	this.configurer.defaultCodecs().jaxb2Decoder(jaxb2Decoder);
	this.configurer.defaultCodecs().jaxb2Encoder(jaxb2Encoder);

	assertDecoderInstance(jacksonDecoder);
	assertDecoderInstance(protobufDecoder);
	assertDecoderInstance(jaxb2Decoder);
	assertEncoderInstance(jacksonEncoder);
	assertEncoderInstance(protobufEncoder);
	assertEncoderInstance(jaxb2Encoder);
}
 
源代码10 项目: bidder   文件: GoogleBidRequest.java
/**
 * Given the input stream, parse and make the class.
 * 
 * @param in InputStream. The content of the POST
 * @throws Exception on protobuf, json or I/O errors.
 */
public GoogleBidRequest(InputStream in) throws Exception {
	int nRead;
	byte[] data = new byte[1024];
	ByteArrayOutputStream buffer = new ByteArrayOutputStream();
	while ((nRead = in.read(data, 0, data.length)) != -1) {
		buffer.write(data, 0, nRead);
	}

	data = buffer.toByteArray();
	if (data.length == 0) {
		notABidRequest = true;
		return;
	}

	ExtensionRegistry registry = ExtensionRegistry.newInstance();
	registry.add(com.google.doubleclick.AdxExt.imp);
	internal = com.google.openrtb.OpenRtb.BidRequest.parseFrom(data, registry);

	// internal = com.google.openrtb.OpenRtb.BidRequest.parseFrom(in);
	doInternal();
}
 
源代码11 项目: gsc-core   文件: JsonFormat.java
/**
 * Parse a text-format message from {@code input} and merge the contents into {@code builder}.
 * Extensions will be recognized if they are registered in {@code extensionRegistry}.
 */
public static void merge(CharSequence input,
                         ExtensionRegistry extensionRegistry,
                         Message.Builder builder, boolean selfType) throws ParseException {
    Tokenizer tokenizer = new Tokenizer(input);

    // Based on the state machine @ http://json.org/

    tokenizer.consume("{"); // Needs to happen when the object starts.
    while (!tokenizer.tryConsume("}")) { // Continue till the object is done
        mergeField(tokenizer, extensionRegistry, builder, selfType);
    }
    // Test to make sure the tokenizer has reached the end of the stream.
    if (!tokenizer.atEnd()) {
        throw tokenizer.parseException(
                "Expecting the end of the stream, but there seems to be more data!  "
                        + "Check the input for a valid JSON format.");
    }
}
 
源代码12 项目: JVoiceXML   文件: TestMmiReceiver.java
/**
     * Set up the test environment.
     * 
     * @throws Exception
     *             set up failed
     */
    @Before
    public void setUp() throws Exception {
        receivingNode = new Node();
        publishingNode = new Node();
        final MmiReceiver receiver = new MmiReceiver("target1");
        receiver.addMMIEventListener(this);
        TypedSubscriber subscriber = new TypedSubscriber("test");
        subscriber.setReceiver(receiver);
        receivingNode.addSubscriber(subscriber);
        // TODO fix this in umundo
//        subscriber.registerType(LifeCycleEvents.LifeCycleEvent.class);

        ExtensionRegistry registry = ExtensionRegistry.newInstance();
        LifeCycleEvents.registerAllExtensions(registry);
        subscriber.setExtensionRegistry(registry);
        lock = new Object();
        receivedEvent = null;
    }
 
源代码13 项目: beam   文件: ProtoCoder.java
/**
 * Validate that all extensionHosts are able to be registered.
 *
 * @param moreExtensionHosts
 */
void validateExtensions(Iterable<Class<?>> moreExtensionHosts) {
  for (Class<?> extensionHost : moreExtensionHosts) {
    // Attempt to access the required method, to make sure it's present.
    try {
      Method registerAllExtensions =
          extensionHost.getDeclaredMethod("registerAllExtensions", ExtensionRegistry.class);
      checkArgument(
          Modifier.isStatic(registerAllExtensions.getModifiers()),
          "Method registerAllExtensions() must be static");
    } catch (NoSuchMethodException | SecurityException e) {
      throw new IllegalArgumentException(
          String.format("Unable to register extensions for %s", extensionHost.getCanonicalName()),
          e);
    }
  }
}
 
源代码14 项目: jigsaw-payment   文件: JavaPropsFormat.java
/**
 * Parse a text-format message from {@code input} and merge the contents
 * into {@code builder}.  Extensions will be recognized if they are
 * registered in {@code extensionRegistry}.
 */
public void merge(final CharSequence input,
                         final ExtensionRegistry extensionRegistry,
                         final Message.Builder builder)
                         throws ParseException {
  final Tokenizer tokenizer = new Tokenizer(input);
  final Map<String, Message> subMessages = new HashMap<String, Message>();

  while (!tokenizer.atEnd()) {
    mergeField(tokenizer, extensionRegistry, subMessages, builder);
  }
}
 
源代码15 项目: beam   文件: ProtobufUtil.java
private static void recursivelyAddDescriptors(
    FieldDescriptor field, Set<Descriptor> descriptors, ExtensionRegistry registry) {
  switch (field.getType()) {
    case BOOL:
    case BYTES:
    case DOUBLE:
    case ENUM:
    case FIXED32:
    case FIXED64:
    case FLOAT:
    case INT32:
    case INT64:
    case SFIXED32:
    case SFIXED64:
    case SINT32:
    case SINT64:
    case STRING:
    case UINT32:
    case UINT64:
      // Primitive types do not transitively access anything else.
      break;

    case GROUP:
    case MESSAGE:
      // Recursively adds all the fields from this nested Message.
      recursivelyAddDescriptors(field.getMessageType(), descriptors, registry);
      break;

    default:
      throw new UnsupportedOperationException(
          "Unexpected Protocol Buffers field type: " + field.getType());
  }
}
 
源代码16 项目: api-compiler   文件: ToolProtoUtil.java
public static FileDescriptorSet openDescriptorSet(String fileName, ExtensionRegistry registry) {
  try {
    return FileDescriptorSet.parseFrom(new FileInputStream(fileName), registry);
  } catch (IOException e) {
    throw new RuntimeException(String.format("Cannot open+parse input file '%s'", fileName), e);
  }
}
 
源代码17 项目: bazel   文件: JavaHeaderCompileActionBuilder.java
/**
 * Creates a consumer that reads the produced .jdeps file into memory. Pulled out into a separate
 * function to avoid capturing a data member, which would keep the entire builder instance alive.
 */
private static Consumer<Pair<ActionExecutionContext, List<SpawnResult>>> createResultConsumer(
    Artifact outputDepsProto) {
  return (Consumer<Pair<ActionExecutionContext, List<SpawnResult>>> & Serializable)
      contextAndResults -> {
        ActionExecutionContext context = contextAndResults.getFirst();
        JavaCompileActionContext javaContext = context.getContext(JavaCompileActionContext.class);
        if (javaContext == null) {
          return;
        }
        SpawnResult spawnResult = Iterables.getOnlyElement(contextAndResults.getSecond());
        try {
          InputStream inMemoryOutput = spawnResult.getInMemoryOutput(outputDepsProto);
          try (InputStream input =
              inMemoryOutput == null
                  ? context.getInputPath(outputDepsProto).getInputStream()
                  : inMemoryOutput) {
            javaContext.insertDependencies(
                outputDepsProto,
                Deps.Dependencies.parseFrom(input, ExtensionRegistry.getEmptyRegistry()));
          }
        } catch (IOException e) {
          // Left empty. If we cannot read the .jdeps file now, we will read it later or throw
          // an appropriate error then.
        }
      };
}
 
源代码18 项目: feeyo-redisproxy   文件: ProtobufDecoder.java
public ProtobufDecoder(T prototype, ExtensionRegistry extensionRegistry, boolean isCustomPkg) {

		if (prototype == null) {
			throw new NullPointerException("prototype");
		}

		this.prototype = prototype.getDefaultInstanceForType();
		this.extensionRegistry = extensionRegistry;
		
		//
		this.isCustomPkg = isCustomPkg;
	}
 
源代码19 项目: jigsaw-payment   文件: JsonJacksonFormat.java
private Object handleObject(JsonParser parser,
                                   ExtensionRegistry extensionRegistry,
                                   Message.Builder builder,
                                   FieldDescriptor field,
                                   ExtensionRegistry.ExtensionInfo extension,
                                   boolean unknown) throws IOException {

    Message.Builder subBuilder;
    if (extension == null) {
        subBuilder = builder.newBuilderForField(field);
    } else {
        subBuilder = extension.defaultInstance.newBuilderForType();
    }

    JsonToken token = parser.getCurrentToken();
    if (JsonToken.VALUE_NULL == token) {
        return null;
    }

    if (unknown) {
    	ByteString data = ByteString.copyFrom(parser.getBinaryValue());
        try {
            subBuilder.mergeFrom(data);
            return subBuilder.build();
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException("Failed to build " + field.getFullName() + " from " + data);
        }
    }

    //token = parser.nextToken();
    if (token.equals(JsonToken.START_OBJECT)) {
     token = parser.nextToken();
     while (token != null && !token.equals(JsonToken.END_OBJECT)) {
         mergeField(parser, extensionRegistry, subBuilder);
         token = parser.nextToken();
     }
    }
    return subBuilder.build();
}
 
源代码20 项目: datacollector   文件: ProtobufTestUtil.java
public static ExtensionRegistry createExtensionRegistry(Map<String, Set<Descriptors.FieldDescriptor>> extensionMap) {
  ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
  for(Map.Entry<String, Set<Descriptors.FieldDescriptor>> e : extensionMap.entrySet()) {
    Set<Descriptors.FieldDescriptor> value = e.getValue();
    for (Descriptors.FieldDescriptor f : value) {
      extensionRegistry.add(f);
    }
  }
  return extensionRegistry;
}
 
源代码21 项目: kogito-runtimes   文件: AbstractKieModule.java
@Override
public CompilationCache getCompilationCache(String kbaseName) {
    // Map< DIALECT, Map< RESOURCE, List<BYTECODE> > >
    CompilationCache cache = compilationCache.get(kbaseName);
    if (cache == null) {
        byte[] fileContents = getBytes(KieBuilderImpl.getCompilationCachePath(releaseId, kbaseName));
        if (fileContents != null) {
            ExtensionRegistry registry = KieModuleCacheHelper.buildRegistry();
            try {
                Header header = KieModuleCacheHelper.readFromStreamWithHeaderPreloaded(new ByteArrayInputStream(fileContents), registry);

                if (!Drools.isCompatible(header.getVersion().getVersionMajor(),
                                         header.getVersion().getVersionMinor(),
                                         header.getVersion().getVersionRevision())) {
                    // if cache has been built with an incompatible version avoid to use it
                    log.warn("The compilation cache has been built with an incompatible version. " +
                             "You should recompile your project in order to use it with current release.");
                    return null;
                }

                KModuleCache kModuleCache = KModuleCache.parseFrom(header.getPayload());

                cache = new CompilationCache();
                for (CompilationData _data : kModuleCache.getCompilationDataList()) {
                    for (CompDataEntry _entry : _data.getEntryList()) {
                        cache.addEntry(_data.getDialect(), _entry.getId(),  _entry.getData().toByteArray());
                    }
                }
                compilationCache.put(kbaseName, cache);
            } catch (Exception e) {
                log.error("Unable to load compilation cache... ", e);
            }
        }
    }
    return cache;
}
 
源代码22 项目: kogito-runtimes   文件: KieModuleCacheHelper.java
public static KieModuleCache.Header readFromStreamWithHeaderPreloaded( InputStream stream, ExtensionRegistry registry ) throws IOException, ClassNotFoundException {
    // we preload the stream into a byte[] to overcome a message size limit
    // imposed by protobuf as per https://issues.jboss.org/browse/DROOLS-25
    byte[] preloaded = preload(stream);
    KieModuleCache.Header _header = KieModuleCache.Header.parseFrom( preloaded, registry );

    // should we check version as well here?
    checkSignature( _header, _header.getPayload().toByteArray() );

    return _header;
}
 
源代码23 项目: j2objc   文件: EnumsTest.java
public void testBadEnumValue() throws Exception {
  ExtensionRegistry registry = ExtensionRegistry.newInstance();
  EnumFields.registerAllExtensions(registry);
  byte[] bytes = asBytes(new int[] {
    0x08, 0x09, 0xA8, 0x01, 0x09, 0xCA, 0x02, 0x01, 0x09, 0xC8, 0x3E, 0x09, 0xE8, 0x3F, 0x09,
    0x8A, 0x41, 0x01, 0x09 });
  EnumMsg msg = EnumMsg.parseFrom(bytes, registry);
  assertFalse(msg.hasEnumF());
  assertEquals(0, msg.getEnumRCount());
  assertEquals(0, msg.getEnumPCount());
  // TODO(kstanger): Native ObjC behavior differs from Java behavior here.
  //assertFalse(msg.hasExtension(EnumFields.enumFe));
  //assertEquals(0, msg.getExtensionCount(EnumFields.enumRe));
  //assertEquals(0, msg.getExtensionCount(EnumFields.enumPe));
}
 
源代码24 项目: bazel   文件: ClassMemberRetargetConfig.java
@Memoized
MethodInvocations invocationReplacementConfigProto() {
  try {
    String protoText = Resources.toString(invocationReplacementConfigUrl(), UTF_8);
    return TextFormat.parse(
        protoText, ExtensionRegistry.getEmptyRegistry(), MethodInvocations.class);
  } catch (IOException e) {
    throw new IOError(e);
  }
}
 
源代码25 项目: kogito-runtimes   文件: PersisterHelper.java
public static ExtensionRegistry buildRegistry(MarshallerReaderContext context, ProcessMarshaller processMarshaller ) {
    ExtensionRegistry registry = ExtensionRegistry.newInstance();
    if( processMarshaller != null ) {
        context.parameterObject = registry;
        processMarshaller.init( context );
    }
    return registry;
}
 
源代码26 项目: kogito-runtimes   文件: ProtobufInputMarshaller.java
private static ProtobufMessages.KnowledgeSession loadAndParseSession(MarshallerReaderContext context) throws IOException,
                                                                                                     ClassNotFoundException {
    ExtensionRegistry registry = PersisterHelper.buildRegistry( context, processMarshaller );

    ProtobufMessages.Header _header = PersisterHelper.readFromStreamWithHeaderPreloaded( context, registry );

    return ProtobufMessages.KnowledgeSession.parseFrom( _header.getPayload(), registry );
}
 
public void init(MarshallerReaderContext context) {
    ExtensionRegistry registry = (ExtensionRegistry) context.parameterObject;
    registry.add( JBPMMessages.processInstance );
    registry.add( JBPMMessages.processTimer );
    registry.add( JBPMMessages.procTimer );
    registry.add( JBPMMessages.workItem );
    registry.add( JBPMMessages.timerId );
}
 
源代码28 项目: j2objc   文件: CompatibilityTest.java
public void testMergeDelimitedFromInvalidProtocolBufferException() throws Exception {
  try {
    ByteArrayInputStream in = new ByteArrayInputStream(new byte[]{ 0x03, 0x01, 0x02 });
    TypicalData.Builder builder = TypicalData.newBuilder();
    builder.mergeDelimitedFrom(in, ExtensionRegistry.getEmptyRegistry());
    builder.build();
    fail("Expected InvalidProtocolBufferException to be thrown.");
  } catch (InvalidProtocolBufferException e) {
    // Expected
  }
}
 
源代码29 项目: grpc-java-contrib   文件: ProtoTypeMapTest.java
@BeforeClass
public static void buildProtoTypeMap() throws IOException {
    // Dump file generated during the maven generate-test-sources phase
    final String dumpPath = "target/generated-test-sources/protobuf/dump/descriptor_dump";

    byte[] generatorRequestBytes = ByteStreams.toByteArray(new FileInputStream(new File(dumpPath)));
    PluginProtos.CodeGeneratorRequest request = PluginProtos.CodeGeneratorRequest.parseFrom(
            generatorRequestBytes, ExtensionRegistry.newInstance());
    List<DescriptorProtos.FileDescriptorProto> fileProtos = request.getProtoFileList();
    protoTypeMap =  ProtoTypeMap.of(fileProtos);
}
 
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
		ExtensionRegistry extensionRegistry, Message.Builder builder)
		throws IOException, HttpMessageConversionException {

	if (contentType.isCompatibleWith(APPLICATION_JSON)) {
		InputStreamReader reader = new InputStreamReader(input, charset);
		this.parser.merge(reader, builder);
	}
	else {
		throw new HttpMessageConversionException(
				"protobuf-java-util does not support parsing " + contentType);
	}
}
 
 类所在包
 同包方法