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    *      https://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.commons.dbcp2.datasources;
19  
20  import java.io.Serializable;
21  import java.util.Arrays;
22  
23  import org.apache.commons.dbcp2.Utils;
24  
25  /**
26   * A {@code char} array wrapper that does not reveal its contents inadvertently through toString(). In contrast to, for example, AtomicReference which
27   * toString()'s its contents.
28   * <p>
29   * May contain null.
30   * </p>
31   *
32   * @since 2.9.0
33   */
34  final class CharArray implements Serializable {
35  
36      static final CharArray NULL = new CharArray((char[]) null);
37      private static final long serialVersionUID = 1L;
38      private final char[] chars;
39  
40      CharArray(final char[] chars) {
41          this.chars = Utils.clone(chars);
42      }
43  
44      CharArray(final String string) {
45          this.chars = Utils.toCharArray(string);
46      }
47  
48      /**
49       * Converts the value of char array as a String.
50       *
51       * @return value as a string, may be null.
52       */
53      String asString() {
54          return Utils.toString(chars);
55      }
56  
57      /**
58       * Clears the content of the char array.
59       *
60       * @return {@code this} instance.
61       */
62      CharArray clear() {
63          if (chars != null) {
64              Arrays.fill(chars, '\0');
65          }
66          return this;
67      }
68  
69      @Override
70      public boolean equals(final Object obj) {
71          if (this == obj) {
72              return true;
73          }
74          if (!(obj instanceof CharArray)) {
75              return false;
76          }
77          final CharArray other = (CharArray) obj;
78          return Arrays.equals(chars, other.chars);
79      }
80  
81      /**
82       * Gets the value of char array.
83       *
84       * @return value, may be null.
85       */
86      char[] get() {
87          return Utils.clone(chars);
88      }
89  
90      @Override
91      public int hashCode() {
92          return Arrays.hashCode(chars);
93      }
94  }