2

I couldnt find a way to mask certain fields in protobuf structure. I did read about the FieldMaskUtil and tried few examples but it seems to do the reverse i.e copy fields which are mentioned in FieldMask which is different from what i wanted. Here's the sample structure and corresponding Test code.

Proto:

syntax = "proto3";

package model;

option java_package = "test.demo.services.protobuf.customer.model";
option java_outer_classname = "CustomerProto";

message Accounts {
  repeated Account account = 1;
}

message Account {

  int32 id = 1;
  string number = 2;
  int32 customer_id = 3;

}

 message Customers {
   repeated Customer customers = 1;
}

message Customer {

  int32 id = 1;
  string pesel = 2;
  string name = 3;
  CustomerType type = 4;
  repeated Account accounts = 5;

  enum CustomerType {
    INDIVIDUAL = 0;
    COMPANY = 1;
  }

}

Here's sample test code

package test.demo.services.protobuf.customer.model;

import org.junit.Test;
import test.demo.services.protobuf.customer.model.CustomerProto.Customer;
import com.google.protobuf.util.FieldMaskUtil;


public class TestMerge {


  @Test
  public void eraseFields() {

        Customer request = Customer.newBuilder().setId(10).setPesel("12345").setName("Harry Alto").build();
    // Erase name
      Customer.Builder modifieldRequest = Customer.newBuilder();
      FieldMaskUtil.merge(FieldMaskUtil.fromString("name"), request, modifieldRequest);
      System.out.println( modifieldRequest.build().toString());
}

}

Here's the output:

name: "Harry Alto"

What i would have expected is to print everything other than name

id: 10
pesel: "12345"

Is there a way to do what i want

4

2 回答 2

2
FieldMaskUtil.merge(FieldMaskUtil.fromString("name"), request, modifieldRequest);

我所期望的是打印除名称以外的所有内容

不,根据 JavaDocs for FieldMask,行为与您描述的相反:

字段掩码用于指定应由 get 操作返回或由更新操作修改的字段子集。

掩码充当集合交集操作,仅选择指定的字段。在您的情况下,掩码仅指定“名称”,这就是它选择的内容。

您正在寻求的行为实际上是一个集合补码操作,选择所有未指定的字段。我不知道 Protobuf API 中的内置方法可以执行此操作。自己实施的选项是:

  • 为要保留的每个命名字段FieldMask使用单独的调用构造多个实例。FieldMask#fromString然后,使用FieldMaskUtil#union来组合所有这些。这将仅保留特别列出的字段。如果您稍后改进架构以添加更多字段,那么它将不会选择这些新字段。您必须更改代码并将新的命名字段添加到该联合中。
  • 调用MessageOrBuilder#getAllFields以获取消息中所有字段的描述符。遍历所有这些,FieldMaskUtil#union如上所述使用,但跳过您要忽略的特定字段,例如“名称”。如果您稍后改进架构以添加更多字段,那么这将选择那些新字段。您无需更改代码即可开始包含这些新字段。

请注意这些解决方案中模式演变方面的差异。选择哪一个最合适取决于您的要求。

于 2017-07-28T16:59:54.300 回答
1

如果您真的希望删除名称字段,您可以这样做:

Customer.Builder request Customer.newBuilder()
    .setId(10).setPesel("12345").setName("Harry Alto").build();
// Erase name
Customer.Builder modifiedRequest = request.toBuilder();
Customer modifyRequest = Customer.getDefaultInstance();
FieldMaskUtil.merge(FieldMaskUtil.fromString("name"), modifyRequest, modifiedRequest);
System.out.println(modifiedRequest.build().toString());

那应该会产生您想要的结果。

于 2017-08-02T23:31:51.477 回答