1 /* 2 * Copyright 2020 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.cloud.aiplatform.util; 18 19 import com.google.protobuf.InvalidProtocolBufferException; 20 import com.google.protobuf.Message; 21 import com.google.protobuf.Value; 22 import com.google.protobuf.util.JsonFormat; 23 24 /** 25 * Exposes utility methods for converting AI Platform messages to and from 26 * {@com.google.protobuf.Value} objects. 27 */ 28 public class ValueConverter { 29 30 /** An empty {@com.google.protobuf.Value} message. */ 31 public static final Value EMPTY_VALUE = Value.newBuilder().build(); 32 33 /** 34 * Converts a message type to a {@com.google.protobuf.Value}. 35 * 36 * @param message the message to convert 37 * @return the message as a {@com.google.protobuf.Value} 38 * @throws InvalidProtocolBufferException 39 */ toValue(Message message)40 public static Value toValue(Message message) throws InvalidProtocolBufferException { 41 String jsonString = JsonFormat.printer().print(message); 42 Value.Builder value = Value.newBuilder(); 43 JsonFormat.parser().merge(jsonString, value); 44 return value.build(); 45 } 46 47 /** 48 * Converts a {@com.google.protobuf.Value} to a {@com.google.protobuf.Message} of the provided 49 * {@com.google.protobuf.Message.Builder}. 50 * 51 * @param messageBuilder a builder for the message type 52 * @param value the Value to convert to a message 53 * @return the value as a message 54 * @throws InvalidProtocolBufferException 55 */ fromValue(Message.Builder messageBuilder, Value value)56 public static Message fromValue(Message.Builder messageBuilder, Value value) 57 throws InvalidProtocolBufferException { 58 String valueString = JsonFormat.printer().print(value); 59 JsonFormat.parser().merge(valueString, messageBuilder); 60 return messageBuilder.build(); 61 } 62 } 63