Java 类com.google.protobuf.TextFormat.ParseException 实例源码

项目:incubator-pulsar    文件:MetaStoreImplZookeeper.java   
@Override
public void asyncGetCursorInfo(String ledgerName, String consumerName,
        final MetaStoreCallback<ManagedCursorInfo> callback) {
    String path = prefix + ledgerName + "/" + consumerName;
    if (log.isDebugEnabled()) {
        log.debug("Reading from {}", path);
    }

    zk.getData(path, false, (rc, path1, ctx, data, stat) -> executor.submit(safeRun(() -> {
        if (rc != Code.OK.intValue()) {
            callback.operationFailed(new MetaStoreException(KeeperException.create(Code.get(rc))));
        } else {
            try {
                ManagedCursorInfo info = parseManagedCursorInfo(data);
                callback.operationComplete(info, new ZKStat(stat));
            } catch (ParseException | InvalidProtocolBufferException e) {
                callback.operationFailed(new MetaStoreException(e));
            }
        }
    })), null);

    if (log.isDebugEnabled()) {
        log.debug("Reading from {} ok", path);
    }
}
项目:bazel    文件:MockCcSupport.java   
/** Applies the given function to the first toolchain that applies to the given cpu. */
public static String applyToToolchain(
    String original,
    String targetCpu,
    Function<CToolchain.Builder, CToolchain.Builder> transformation)
    throws ParseException {
  CrosstoolConfig.CrosstoolRelease.Builder crosstoolBuilder =
      CrosstoolConfig.CrosstoolRelease.newBuilder();
  TextFormat.merge(original, crosstoolBuilder);
  for (int i = 0; i < crosstoolBuilder.getToolchainCount(); i++) {
    if (crosstoolBuilder.getToolchain(i).getTargetCpu().equals(targetCpu)) {
      CToolchain.Builder toolchainBuilder =
          CToolchain.newBuilder(crosstoolBuilder.getToolchain(i));
      transformation.apply(toolchainBuilder);
      crosstoolBuilder.removeToolchain(i);
      crosstoolBuilder.addToolchain(toolchainBuilder.build());
      break;
    }
  }

  return TextFormat.printToString(crosstoolBuilder.build());
}
项目:bazel    文件:UnknownEnumValueTest.java   
public void testUnknownEnumValuesInTextFormat() {
  TestAllTypes.Builder builder = TestAllTypes.newBuilder();
  builder.setOptionalNestedEnumValue(4321);
  builder.addRepeatedNestedEnumValue(5432);
  builder.addPackedNestedEnumValue(6543);
  TestAllTypes message = builder.build();

  // We can print a message with unknown enum values.
  String textData = TextFormat.printToString(message);
  assertEquals(
      "optional_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_4321\n"
      + "repeated_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_5432\n"
      + "packed_nested_enum: UNKNOWN_ENUM_VALUE_NestedEnum_6543\n", textData);

  // Parsing unknown enum values will fail just like parsing other kinds of
  // unknown fields.
  try {
    TextFormat.merge(textData, builder);
    fail();
  } catch (ParseException e) {
    // expected.
  }
}
项目:incubator-pulsar    文件:MetaStoreImplZookeeper.java   
private ManagedLedgerInfo parseManagedLedgerInfo(byte[] data)
        throws ParseException, InvalidProtocolBufferException {
    // First try binary format, then fallback to text
    try {
        return ManagedLedgerInfo.parseFrom(data);
    } catch (InvalidProtocolBufferException e) {
        // Fallback to parsing protobuf text format
        ManagedLedgerInfo.Builder builder = ManagedLedgerInfo.newBuilder();
        TextFormat.merge(new String(data, Encoding), builder);
        return builder.build();
    }
}
项目:incubator-pulsar    文件:MetaStoreImplZookeeper.java   
private ManagedCursorInfo parseManagedCursorInfo(byte[] data)
        throws ParseException, InvalidProtocolBufferException {
    // First try binary format, then fallback to text
    try {
        return ManagedCursorInfo.parseFrom(data);
    } catch (InvalidProtocolBufferException e) {
        // Fallback to parsing protobuf text format
        ManagedCursorInfo.Builder builder = ManagedCursorInfo.newBuilder();
        TextFormat.merge(new String(data, Encoding), builder);
        return builder.build();
    }

}
项目:api-compiler    文件:TestConfig.java   
/** Parses the config file, in proto text format, and returns it. */
public Service getApiProtoConfig(String configFileName) throws ParseException {
  String content = readTestData(configFileName);
  Service.Builder builder = Service.newBuilder();
  TextFormat.merge(content, builder);
  return builder.build();
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean primitive(Object value) throws ParseException, IOException
{
  if (getMatchKeyList().contains(key)) {
    found = true;
    this.value = value;
    keyValMap.put(key, value);
    key = null;
    keyCount++;
    return false;
  }
  return true;
}
项目:bdclient    文件:InfoTalk.java   
/**
 * Handle a request, customized by an user's protocol
 * 
 * @param uid
 * @param ip
 * @param app
 * @param apv
 * @param os
 * @param osv
 * @param ch
 * @param op
 * @param nation
 * @param province
 * @param city
 * @throws ParseException
 * @throws InvalidProtocolBufferException
 * @throws Exception
 */
public void handle(String uid, String ip, String app, String apv, String os, String osv,
        String ch, String op, String nation, String province, String city)
        throws ParseException, InvalidProtocolBufferException, Exception
{
    InfoReqPack.Builder builder = InfoReqPack.newBuilder();
    if (null != uid && !"".equals(uid))
        builder.setUid(uid);
    if (null != ip && !"".equals(ip))
        builder.setIp(ip);
    if (null != app && !"".equals(app))
        builder.setApp(app);
    if (null != apv && !"".equals(apv))
        builder.setAppVer(apv);
    if (null != os && !"".equals(os))
        builder.setOs(os);
    if (null != osv && !"".equals(osv))
        builder.setOsVer(osv);
    if (null != ch && !"".equals(ch))
        builder.setChannel(ch);
    if (null != op && !"".equals(op))
        builder.setIsp(op);
    if (null != nation && !"".equals(nation))
        builder.setNation(nation);
    if (null != province && !"".equals(province))
        builder.setProvince(province);
    if (null != city && !"".equals(city))
        builder.setCity(city);
    builder.setLocSwitch(true);
    InfoReqPack pack = builder.build();
    // if (ClientMgr.getInstance().send("ADAPTER", pack, this)) {
    if (ClientMgr.getInstance().send("INFO", pack, this)) {
         log.info("REQ succ:" + this.m_checkSum);
    } else {
        log.info("REQ failed:" + this.m_checkSum);
        throw new Exception("send fail");
    }
}
项目:esj    文件:Writer.java   
public void writeMultipleEvents() throws Exception, ParseException {
    final int TOTAL_WRITES = 100000;
    final long startTime = System.currentTimeMillis();
    successes = 0;
    fails = 0;

    for (int z = 0; z < TOTAL_WRITES; z++) {
        es.appendToStream(STREAM_NAME, new ResponseReceiver() {

            @Override
            public void onResponseReturn(Message msg) {
                // log.debug("Response returned="+i);
                successes++;
                if ((successes + fails) == (TOTAL_WRITES)) {
                    processing.release();
                }
            }

            @Override
            public void onErrorReturn(Exception ex) {
                fails++;
                if ((successes + fails) == TOTAL_WRITES) {
                    processing.release();
                }
            }
        }, generateEvents());
    }

    processing.acquire();
    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    log.debug("Writing finished. Number of writes={} ({} successful, {} failed), duration={}",
                    TOTAL_WRITES, successes, fails, duration);
}
项目:esj    文件:EventSendIT.java   
@Test
public void writeMultipleEvents() throws Exception, ParseException {
    final int TOTAL_WRITES = 100000;
    final long startTime = System.currentTimeMillis();
    successes = 0;
    fails = 0;

    for (int z = 0; z < TOTAL_WRITES; z++) {
        es.appendToStream(STREAM_NAME, new ResponseReceiver() {

            @Override
            public void onResponseReturn(Message msg) {
                // log.debug("Response returned="+i);
                successes++;
                if ((successes + fails) == (TOTAL_WRITES)) {
                    processing.release();
                }
            }

            @Override
            public void onErrorReturn(Exception ex) {
                fails++;
                if ((successes + fails) == TOTAL_WRITES) {
                    processing.release();
                }
            }
        }, generateEvents());
    }

    processing.acquire();
    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    log.debug("Writing finished. Number of writes={} ({} successful, {} failed), duration={}",
                    TOTAL_WRITES, successes, fails, duration);
}
项目:closure-compiler    文件:CheckConformanceTest.java   
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
  ConformanceConfig.Builder builder = ConformanceConfig.newBuilder();
  try {
    TextFormat.merge(configuration, builder);
  } catch (ParseException e) {
    throw new RuntimeException(e);
  }
  return new CheckConformance(compiler, ImmutableList.of(builder.build()));
}
项目:closure-templates    文件:SoyConformanceTest.java   
private ValidatedConformanceConfig parseConfigProto(String textProto) {
  ConformanceConfig.Builder builder = ConformanceConfig.newBuilder();
  try {
    TextFormat.merge(textProto, builder);
  } catch (ParseException pe) {
    throw new RuntimeException(pe);
  }
  return ValidatedConformanceConfig.create(builder.build());
}
项目:bazel    文件:RemoteSpawnRunner.java   
static Platform parsePlatform(Label platformLabel, @Nullable String platformDescription) {
  Platform.Builder platformBuilder = Platform.newBuilder();
  try {
    if (platformDescription != null) {
      TextFormat.getParser().merge(platformDescription, platformBuilder);
    }
  } catch (ParseException e) {
    throw new IllegalArgumentException(
        String.format(
            "Failed to parse remote_execution_properties from platform %s", platformLabel),
        e);
  }
  return platformBuilder.build();
}
项目:bazel    文件:MockCcSupport.java   
public static String mergeCrosstoolConfig(String original, CToolchain toolchain)
    throws TextFormat.ParseException {
  CrosstoolConfig.CrosstoolRelease.Builder builder =
      CrosstoolConfig.CrosstoolRelease.newBuilder();
  TextFormat.merge(original, builder);
  for (CToolchain.Builder toolchainBuilder : builder.getToolchainBuilderList()) {
    toolchainBuilder.mergeFrom(toolchain);
  }
  return TextFormat.printToString(builder.build());
}
项目:bazel    文件:MockCcSupport.java   
public static String addLibcLabelToCrosstool(String original, String label)
    throws TextFormat.ParseException {
  CrosstoolConfig.CrosstoolRelease.Builder builder =
      CrosstoolConfig.CrosstoolRelease.newBuilder();
  TextFormat.merge(original, builder);
  for (CrosstoolConfig.CToolchain.Builder toolchain : builder.getToolchainBuilderList()) {
    toolchain.setDefaultGrteTop(label);
  }
  return TextFormat.printToString(builder.build());
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public void startJSON() throws ParseException, IOException
{
  found = false;
  end = false;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public void endJSON() throws ParseException, IOException
{
  end = true;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean startArray() throws ParseException, IOException
{
  return true;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean startObject() throws ParseException, IOException
{
  return true;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean startObjectEntry(String key) throws ParseException, IOException
{
  this.key = key;
  return true;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean endArray() throws ParseException, IOException
{
  return false;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean endObject() throws ParseException, IOException
{
  return true;
}
项目:apex-malhar    文件:JsonKeyFinder.java   
public boolean endObjectEntry() throws ParseException, IOException
{
  return true;
}
项目:GDSC-SMLM    文件:PSFProtosTest.java   
@Test
public void canWriteAndReadString() throws ParseException, InvalidProtocolBufferException
{
    PSFProtos.PSF.Builder psfBuilder = PSFProtos.PSF.newBuilder();
    PSFParameter.Builder psfParamBuilder = PSFProtos.PSFParameter.newBuilder();
    psfBuilder.setPsfType(PSFType.TWO_AXIS_AND_THETA_GAUSSIAN_2D);
    psfParamBuilder.setName("X\"SD");
    psfParamBuilder.setUnit(PSFParameterUnit.DISTANCE);
    psfParamBuilder.setValue(1.1);
    psfBuilder.addParameters(psfParamBuilder);
    psfParamBuilder.setName("Y SD");
    psfParamBuilder.setUnit(PSFParameterUnit.DISTANCE);
    psfParamBuilder.setValue(1.2);
    psfBuilder.addParameters(psfParamBuilder);
    psfParamBuilder.setName("'Angle");
    psfParamBuilder.setUnit(PSFParameterUnit.ANGLE);
    psfParamBuilder.clearValue();
    psfBuilder.addParameters(psfParamBuilder);

    // Standard string
    String e = psfBuilder.toString();
    PSFProtos.PSF psf = psfBuilder.build();
    String o = psf.toString();
    System.out.printf(o);
    Assert.assertEquals(e, o);

    psfBuilder.clear();
    TextFormat.merge(o, psfBuilder);
    Assert.assertTrue("Merge string", psf.equals(psfBuilder.build()));

    // Short string
    String o2 = TextFormat.shortDebugString(psf);
    System.out.println(o2);

    psfBuilder.clear();
    TextFormat.merge(o2, psfBuilder);
    Assert.assertTrue("Merge short string", psf.equals(psfBuilder.build()));

    // JSON
    Printer printer = JsonFormat.printer().omittingInsignificantWhitespace();
    String json = printer.print(psf);
    System.out.println(json);
    json = JSONUtils.simplify(json);
    System.out.println(json);

    psfBuilder.clear();
    JsonFormat.parser().merge(json, psfBuilder);
    Assert.assertTrue("Merge JSON", psf.equals(psfBuilder.build()));
}
项目:protobuf-el    文件:AggregateValueTextFormatTest.java   
@Test
public void testMergeCharSequenceExtensionRegistryBuilder() throws ParseException,
    URISyntaxException {
  final Map<String, FileDescriptor> info1 =
      ProtoFiles
          .newBuilder()
          .addFiles(new File(getClass().getResource("protoc-misc/").toURI()),
              "DeepAggregateOptionValue1.proto").build();

  final String protoSource =
      new StringBuilder().append("message Message1 {").append(NL)
          .append("  optional string f1 = 1;").append(NL).append("  optional Message2 f2 = 2;")
          .append(NL).append("}").append(NL).append("").append(NL).append("message Message2 {")
          .append(NL).append(" optional string f21 = 1;").append(NL)
          .append(" optional string f22 = 2;").append(NL).append("}").append(NL).toString();

  final Map<String, FileDescriptor> info =
      ProtoFiles.newBuilder().addSource("DeepAggregateOptionValue1.proto", protoSource).build();
  final Descriptor type =
      info.get("DeepAggregateOptionValue1.proto").findMessageTypeByName("Message1");

  final FieldDescriptor f1FD = type.findFieldByName("f1");
  final FieldDescriptor f2FD = type.findFieldByName("f2");
  final Descriptor type2 = f2FD.getMessageType();

  final DynamicMessage expected =
      DynamicMessage
          .newBuilder(type)
          .setField(f1FD, "hello")
          .setField(
              f2FD,
              DynamicMessage.newBuilder(type2).setField(type2.findFieldByName("f21"), "deep1")
                  .setField(type2.findFieldByName("f22"), "deep2").build()).build();

  final DynamicMessage.Builder builder = DynamicMessage.newBuilder(type);
  final String input = "f1:'hello' f2 {f21:'deep1' f22:'deep2'}";
  final ExtensionRegistry extensionRegistry = ExtensionRegistry.getEmptyRegistry();

  TextFormat.merge(input, extensionRegistry, builder);
  final DynamicMessage actual = builder.build();

  assertThat(actual, equalTo(expected));
}