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 * Constructor of Method 46 */ EscapeCharacter()47 private EscapeCharacter() { 48 } 49 50 /** 51 * Base number 52 */ 53 private static final int RADIX_NUM = 16; 54 55 /** 56 * Phase string which is escaped 57 * @param src escaped string 58 * @return string after unescape. 59 */ unescape(String src)60 public static String unescape(String src) { 61 StringBuffer tmp = new StringBuffer(); 62 tmp.ensureCapacity(src.length()); 63 int lastPos = 0; 64 int pos = 0; 65 while (lastPos < src.length()) { 66 pos = src.indexOf('%', lastPos); 67 if (pos == lastPos) { 68 if (src.charAt(pos + 1) == 'u') { 69 char ch = (char) Integer.parseInt(src.substring(pos + ESCAPE_STRING2_LEN, 70 pos + ESCAPE_STRING2_LEN + INTERCEPT2_LEN), RADIX_NUM); 71 tmp.append(ch); 72 lastPos = pos + ESCAPE_STRING2_LEN + INTERCEPT2_LEN; 73 } else { 74 char ch = (char) Integer.parseInt(src.substring(pos + ESCAPE_STRING1_LEN, 75 pos + ESCAPE_STRING1_LEN + INTERCEPT1_LEN), RADIX_NUM); 76 tmp.append(ch); 77 lastPos = pos + ESCAPE_STRING1_LEN + INTERCEPT1_LEN; 78 } 79 } else if (pos == -1) { 80 tmp.append(src.substring(lastPos)); 81 lastPos = src.length(); 82 } else { 83 tmp.append(src.substring(lastPos, pos)); 84 lastPos = pos; 85 } 86 } 87 return tmp.toString(); 88 } 89 } 90