1 /* 2 * Copyright 2018 LINE Corporation 3 * 4 * LINE Corporation licenses this file to you under the Apache License, 5 * version 2.0 (the "License"); you may not use this file except in compliance 6 * with the License. You may obtain a copy of the License at: 7 * 8 * https://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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 */ 16 17 package com.linecorp.centraldogma.internal.jsonpatch; 18 19 import static java.util.Objects.requireNonNull; 20 21 /** 22 * A utility class for JSON patch operation. 23 */ 24 public final class JsonPatchUtil { 25 26 /** 27 * Adds a leading slash and replaces '/' and '~' with '~1' and '~0' respectively. 28 * See <a href="https://tools.ietf.org/html/rfc6901">rfc6901</a> for more information. 29 */ 30 public static String encodeSegment(String segment) { 31 requireNonNull(segment, "segment"); 32 final StringBuilder sb = new StringBuilder(segment.length() + 1); 33 sb.append('/'); 34 for (int i = 0, end = segment.length(); i < end; ++i) { 35 final char c = segment.charAt(i); 36 if (c == '/') { 37 sb.append("~1"); 38 continue; 39 } 40 if (c == '~') { 41 sb.append("~0"); 42 continue; 43 } 44 sb.append(c); 45 } 46 return sb.toString(); 47 } 48 49 private JsonPatchUtil() {} 50 }