1 /* 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 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 16 package com.ohos.hapsigntool.utils; 17 18 /** 19 * Provider function of escape character. 20 * 21 * @since 2021/12/21 22 */ 23 public class EscapeCharacter { 24 /** 25 * The length of character "%" 26 */ 27 private static final int ESCAPE_STRING1_LEN = 1; 28 29 /** 30 * The length of character "%u" 31 */ 32 private static final int ESCAPE_STRING2_LEN = 2; 33 34 /** 35 * If it starts with "%", the intercept length is 2 36 */ 37 private static final int INTERCEPT1_LEN = 2; 38 39 /** 40 * If it starts with "%u", the intercept length is 4 41 */ 42 private static final int INTERCEPT2_LEN = 4; 43 44 /** 45 * Base number 46 */ 47 private static final int RADIX_NUM = 16; 48 49 /** 50 * Constructor of Method 51 */ EscapeCharacter()52 private EscapeCharacter() { 53 } 54 55 /** 56 * Phase string which is escaped 57 * 58 * @param src escaped string 59 * @return string after unescape. 60 */ unescape(String src)61 public static String unescape(String src) { 62 StringBuilder tmp = new StringBuilder(); 63 tmp.ensureCapacity(src.length()); 64 int lastPos = 0; 65 int pos = 0; 66 while (lastPos < src.length()) { 67 pos = src.indexOf('%', lastPos); 68 if (pos == lastPos) { 69 if (src.charAt(pos + 1) == 'u') { 70 char ch = (char) Integer.parseInt(src.substring(pos + ESCAPE_STRING2_LEN, 71 pos + ESCAPE_STRING2_LEN + INTERCEPT2_LEN), RADIX_NUM); 72 tmp.append(ch); 73 lastPos = pos + ESCAPE_STRING2_LEN + INTERCEPT2_LEN; 74 } else { 75 char ch = (char) Integer.parseInt(src.substring(pos + ESCAPE_STRING1_LEN, 76 pos + ESCAPE_STRING1_LEN + INTERCEPT1_LEN), RADIX_NUM); 77 tmp.append(ch); 78 lastPos = pos + ESCAPE_STRING1_LEN + INTERCEPT1_LEN; 79 } 80 } else if (pos == -1) { 81 tmp.append(src.substring(lastPos)); 82 lastPos = src.length(); 83 } else { 84 tmp.append(src.substring(lastPos, pos)); 85 lastPos = pos; 86 } 87 } 88 return tmp.toString(); 89 } 90 } 91