1 // Copyright 2020 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package com.google.api.generator.gapic.protoparser; 16 17 import com.google.common.base.Strings; 18 import com.google.gson.Gson; 19 import com.google.gson.GsonBuilder; 20 import com.google.protobuf.InvalidProtocolBufferException; 21 import com.google.protobuf.util.JsonFormat; 22 import java.io.File; 23 import java.io.IOException; 24 import java.nio.charset.StandardCharsets; 25 import java.nio.file.Files; 26 import java.nio.file.Paths; 27 import java.util.LinkedHashMap; 28 import java.util.Map; 29 import java.util.Optional; 30 import org.yaml.snakeyaml.LoaderOptions; 31 import org.yaml.snakeyaml.Yaml; 32 import org.yaml.snakeyaml.constructor.SafeConstructor; 33 34 public class ServiceYamlParser { parse(String serviceYamlFilePath)35 public static Optional<com.google.api.Service> parse(String serviceYamlFilePath) { 36 if (Strings.isNullOrEmpty(serviceYamlFilePath) || !(new File(serviceYamlFilePath)).exists()) { 37 return Optional.empty(); 38 } 39 40 String fileContents = null; 41 try { 42 fileContents = 43 new String(Files.readAllBytes(Paths.get(serviceYamlFilePath)), StandardCharsets.UTF_8); 44 } catch (IOException e) { 45 return Optional.empty(); 46 } 47 48 Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); 49 Map<String, Object> yamlMap = yaml.load(fileContents); 50 Gson gson = new GsonBuilder().setPrettyPrinting().setLenient().create(); 51 String jsonString = gson.toJson(yamlMap, LinkedHashMap.class); 52 // Use the full name instead of an import, to avoid reader confusion with this and 53 // model.Service. 54 com.google.api.Service.Builder serviceBuilder = com.google.api.Service.newBuilder(); 55 try { 56 JsonFormat.parser().ignoringUnknownFields().merge(jsonString, serviceBuilder); 57 } catch (InvalidProtocolBufferException e) { 58 return Optional.empty(); 59 } 60 return Optional.of(serviceBuilder.build()); 61 } 62 } 63