View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.mask.algorithm.cover;
19  
20  import com.google.common.base.Strings;
21  import org.apache.shardingsphere.mask.algorithm.MaskAlgorithmPropertiesChecker;
22  import org.apache.shardingsphere.mask.spi.MaskAlgorithm;
23  
24  import java.util.Properties;
25  
26  /**
27   * Mask after special-chars algorithm.
28   */
29  public final class MaskAfterSpecialCharsAlgorithm implements MaskAlgorithm<Object, String> {
30      
31      private static final String SPECIAL_CHARS = "special-chars";
32      
33      private static final String REPLACE_CHAR = "replace-char";
34      
35      private String specialChars;
36      
37      private Character replaceChar;
38      
39      @Override
40      public void init(final Properties props) {
41          specialChars = createSpecialChars(props);
42          replaceChar = createReplaceChar(props);
43      }
44      
45      private String createSpecialChars(final Properties props) {
46          MaskAlgorithmPropertiesChecker.checkAtLeastOneChar(props, SPECIAL_CHARS, this);
47          return props.getProperty(SPECIAL_CHARS);
48      }
49      
50      private Character createReplaceChar(final Properties props) {
51          MaskAlgorithmPropertiesChecker.checkSingleChar(props, REPLACE_CHAR, this);
52          return props.getProperty(REPLACE_CHAR).charAt(0);
53      }
54      
55      @Override
56      public String mask(final Object plainValue) {
57          String result = null == plainValue ? null : String.valueOf(plainValue);
58          if (Strings.isNullOrEmpty(result)) {
59              return result;
60          }
61          int index = result.contains(specialChars) ? result.indexOf(specialChars) + specialChars.length() : -1;
62          char[] chars = result.toCharArray();
63          for (int i = index; i != -1 && i < chars.length; i++) {
64              chars[i] = replaceChar;
65          }
66          return new String(chars);
67      }
68      
69      @Override
70      public String getType() {
71          return "MASK_AFTER_SPECIAL_CHARS";
72      }
73  }