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.engine.ast; 16 17 import com.google.auto.value.AutoValue; 18 import com.google.common.escape.Escaper; 19 import com.google.common.escape.Escapers; 20 21 @AutoValue 22 public abstract class StringObjectValue implements ObjectValue { 23 @Override value()24 public abstract String value(); 25 26 @Override type()27 public TypeNode type() { 28 return TypeNode.STRING; 29 } 30 builder()31 public static Builder builder() { 32 return new AutoValue_StringObjectValue.Builder(); 33 } 34 withValue(String value)35 public static StringObjectValue withValue(String value) { 36 return builder().setValue(value).build(); 37 } 38 39 @AutoValue.Builder 40 public abstract static class Builder { setValue(String value)41 public abstract Builder setValue(String value); 42 43 // Private accessors. value()44 abstract String value(); 45 autoBuild()46 public abstract StringObjectValue autoBuild(); 47 build()48 public StringObjectValue build() { 49 // `\"` is added to the escaped string value for interpreting it correctly in file. 50 String value = String.format("\"%s\"", StringValueEscaper.escaper.escape(value())); 51 setValue(value); 52 return autoBuild(); 53 } 54 } 55 56 private static class StringValueEscaper extends Escaper { 57 private static final Escaper escaper = 58 Escapers.builder() 59 .addEscape('\t', "\\t") 60 .addEscape('\b', "\\b") 61 .addEscape('\n', "\\n") 62 .addEscape('\r', "\\r") 63 .addEscape('\f', "\\f") 64 .addEscape('"', "\\\"") 65 .addEscape('\\', "\\\\") 66 .build(); 67 StringValueEscaper()68 private StringValueEscaper() {} 69 70 @Override escape(String sourceString)71 public String escape(String sourceString) { 72 return escaper.escape(sourceString); 73 } 74 } 75 } 76