View Javadoc
1   /*
2    * #%L
3    * IOUtils.java - mongodb-async-driver - Allanbank Consulting, Inc.
4    * %%
5    * Copyright (C) 2011 - 2014 Allanbank Consulting, Inc.
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * 
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   * 
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package com.allanbank.mongodb.util;
21  
22  import java.io.Closeable;
23  import java.io.IOException;
24  import java.util.Arrays;
25  import java.util.logging.Level;
26  
27  import com.allanbank.mongodb.util.log.Log;
28  import com.allanbank.mongodb.util.log.LogFactory;
29  
30  /**
31   * IOUtils provides helper methods for dealing with I/O operations.
32   * 
33   * @api.no This class is <b>NOT</b> part of the drivers API. This class may be
34   *         mutated in incompatible ways between any two releases of the driver.
35   * @copyright 2012-2013, Allanbank Consulting, Inc., All Rights Reserved
36   */
37  public final class IOUtils {
38  
39      /** Base64 encoding array according to RFC 2045. */
40      private static final char[] BASE_64_CHARS = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41              + "abcdefghijklmnopqrstuvwxyz0123456789+/").toCharArray();
42  
43      /**
44       * The mapping from a character (ascii) value to the corresponding Base64
45       * (RFC-2045) 6-bit value.
46       */
47      private static final byte CHAR_TO_BASE_64_BITS[] = { -1, -1, -1, -1, -1,
48              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
49              -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
50              -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
51              60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
52              10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
53              -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
54              38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
55  
56      /** The mapping from a character (ascii) value to a nibble hex encoded. */
57      private static final byte[] CHAR_TO_HEX_NIBBLE;
58  
59      /** Hex encoding characters. */
60      private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
61  
62      /** The logger for the {@link IOUtils}. */
63      private static final Log LOG = LogFactory.getLog(IOUtils.class);
64  
65      static {
66          CHAR_TO_HEX_NIBBLE = new byte[128];
67          Arrays.fill(CHAR_TO_HEX_NIBBLE, (byte) -1);
68          CHAR_TO_HEX_NIBBLE['0'] = 0;
69          CHAR_TO_HEX_NIBBLE['1'] = 1;
70          CHAR_TO_HEX_NIBBLE['2'] = 2;
71          CHAR_TO_HEX_NIBBLE['3'] = 3;
72          CHAR_TO_HEX_NIBBLE['4'] = 4;
73          CHAR_TO_HEX_NIBBLE['5'] = 5;
74          CHAR_TO_HEX_NIBBLE['6'] = 6;
75          CHAR_TO_HEX_NIBBLE['7'] = 7;
76          CHAR_TO_HEX_NIBBLE['8'] = 8;
77          CHAR_TO_HEX_NIBBLE['9'] = 9;
78          CHAR_TO_HEX_NIBBLE['a'] = 0xa;
79          CHAR_TO_HEX_NIBBLE['b'] = 0xb;
80          CHAR_TO_HEX_NIBBLE['c'] = 0xc;
81          CHAR_TO_HEX_NIBBLE['d'] = 0xd;
82          CHAR_TO_HEX_NIBBLE['e'] = 0xe;
83          CHAR_TO_HEX_NIBBLE['f'] = 0xf;
84          CHAR_TO_HEX_NIBBLE['A'] = 0xA;
85          CHAR_TO_HEX_NIBBLE['B'] = 0xB;
86          CHAR_TO_HEX_NIBBLE['C'] = 0xC;
87          CHAR_TO_HEX_NIBBLE['D'] = 0xD;
88          CHAR_TO_HEX_NIBBLE['E'] = 0xE;
89          CHAR_TO_HEX_NIBBLE['F'] = 0xF;
90      }
91  
92      /**
93       * Converts the Base64 (RFC 2045) String into a byte array.
94       * 
95       * @param base64
96       *            The Base64 string to convert.
97       * @return The byte[] version.
98       */
99      public static byte[] base64ToBytes(final String base64) {
100         final int base64Length = base64.length();
101         final int numGroups = base64Length / 4;
102         if ((4 * numGroups) != base64Length) {
103             throw new IllegalArgumentException(
104                     "String length must be a multiple of four.");
105         }
106 
107         int missingBytesInLastGroup = 0;
108         int numFullGroups = numGroups;
109         if (base64Length != 0) {
110             if (base64.charAt(base64Length - 1) == '=') {
111                 missingBytesInLastGroup++;
112                 numFullGroups--;
113             }
114             if (base64.charAt(base64Length - 2) == '=') {
115                 missingBytesInLastGroup++;
116             }
117         }
118         final byte[] result = new byte[(3 * numGroups)
119                 - missingBytesInLastGroup];
120 
121         // Translate all 4 character groups from base64 to byte array elements
122         int base64Index = 0;
123         int resultIndex = 0;
124         for (int i = 0; i < numFullGroups; i++) {
125             final int b1 = alphabetToBits(CHAR_TO_BASE_64_BITS,
126                     base64.charAt(base64Index++));
127             final int b2 = alphabetToBits(CHAR_TO_BASE_64_BITS,
128                     base64.charAt(base64Index++));
129             final int b3 = alphabetToBits(CHAR_TO_BASE_64_BITS,
130                     base64.charAt(base64Index++));
131             final int b4 = alphabetToBits(CHAR_TO_BASE_64_BITS,
132                     base64.charAt(base64Index++));
133             result[resultIndex++] = (byte) ((b1 << 2) + (b2 >> 4));
134             result[resultIndex++] = (byte) ((b2 << 4) + (b3 >> 2));
135             result[resultIndex++] = (byte) ((b3 << 6) + b4);
136         }
137 
138         // Translate partial group, if present
139         if (missingBytesInLastGroup != 0) {
140             final int b1 = alphabetToBits(CHAR_TO_BASE_64_BITS,
141                     base64.charAt(base64Index++));
142             final int b2 = alphabetToBits(CHAR_TO_BASE_64_BITS,
143                     base64.charAt(base64Index++));
144             result[resultIndex++] = (byte) ((b1 << 2) + (b2 >> 4));
145 
146             if (missingBytesInLastGroup == 1) {
147                 final int b3 = alphabetToBits(CHAR_TO_BASE_64_BITS,
148                         base64.charAt(base64Index++));
149                 result[resultIndex++] = (byte) ((b2 << 4) + (b3 >> 2));
150             }
151         }
152 
153         return result;
154     }
155 
156     /**
157      * Closes the {@link Closeable} and logs any error.
158      * 
159      * @param closeable
160      *            The connection to close.
161      */
162     public static void close(final Closeable closeable) {
163         if (closeable != null) {
164             close(closeable, Level.FINE, "I/O Exception closing: "
165                     + closeable.getClass().getSimpleName());
166         }
167     }
168 
169     /**
170      * Closes the {@link Closeable} and logs any error.
171      * 
172      * @param closeable
173      *            The connection to close.
174      * @param level
175      *            The level to log on a failure.
176      * @param message
177      *            The message to log on a failure.
178      */
179     public static void close(final Closeable closeable, final Level level,
180             final String message) {
181         if (closeable != null) {
182             try {
183                 closeable.close();
184             }
185             catch (final IOException ignored) {
186                 LOG.log(level, message);
187             }
188         }
189     }
190 
191     /**
192      * Converts the hex string to bytes.
193      * 
194      * @param hex
195      *            The HEX string to convert.
196      * @return The byte[] version.
197      */
198     public static byte[] hexToBytes(final String hex) {
199         final String trimmed = hex.trim();
200 
201         final int length = trimmed.length();
202         if ((length & 1) == 1) {
203             throw new IllegalArgumentException(
204                     "A hex string must be an even number of characters: '"
205                             + trimmed + "'");
206         }
207 
208         final byte[] bytes = new byte[length >> 1];
209         for (int i = 0; i < length; i += 2) {
210 
211             final int v1 = alphabetToBits(CHAR_TO_HEX_NIBBLE, trimmed.charAt(i));
212             final int v2 = alphabetToBits(CHAR_TO_HEX_NIBBLE,
213                     trimmed.charAt(i + 1));
214 
215             bytes[i >> 1] = (byte) (((v1 << 4) & 0xF0) + (v2 & 0x0F));
216         }
217 
218         return bytes;
219     }
220 
221     /**
222      * Converts the byte array into a Base64 (RFC 2045) string.
223      * 
224      * @param bytes
225      *            The bytes to convert.
226      * @return The string version.
227      */
228     public static String toBase64(final byte[] bytes) {
229         final int length = bytes.length;
230 
231         // Create a buffer with the maximum possible length.
232         final StringBuffer result = new StringBuffer(4 * ((length + 2) / 3));
233 
234         // Handle each 3 byte group.
235         int index = 0;
236         final int numGroups = length / 3;
237         for (int i = 0; i < numGroups; i++) {
238             final int byte0 = bytes[index++] & 0xff;
239             final int byte1 = bytes[index++] & 0xff;
240             final int byte2 = bytes[index++] & 0xff;
241             result.append(BASE_64_CHARS[byte0 >> 2]);
242             result.append(BASE_64_CHARS[((byte0 << 4) & 0x3f) | (byte1 >> 4)]);
243             result.append(BASE_64_CHARS[((byte1 << 2) & 0x3f) | (byte2 >> 6)]);
244             result.append(BASE_64_CHARS[byte2 & 0x3f]);
245         }
246 
247         // Partial group with padding.
248         final int numBytesInLastGroup = length - (3 * numGroups);
249         if (numBytesInLastGroup > 0) {
250             final int byte0 = bytes[index++] & 0xff;
251             result.append(BASE_64_CHARS[byte0 >> 2]);
252             if (numBytesInLastGroup == 1) {
253                 result.append(BASE_64_CHARS[(byte0 << 4) & 0x3f]);
254                 result.append("==");
255             }
256             else {
257                 final int byte1 = bytes[index++] & 0xff;
258                 result.append(BASE_64_CHARS[((byte0 << 4) & 0x3f)
259                         | (byte1 >> 4)]);
260                 result.append(BASE_64_CHARS[(byte1 << 2) & 0x3f]);
261                 result.append('=');
262             }
263         }
264 
265         return result.toString();
266     }
267 
268     /**
269      * Converts the byte array into a HEX string.
270      * 
271      * @param bytes
272      *            The bytes to convert.
273      * @return The string version.
274      */
275     public static String toHex(final byte[] bytes) {
276         final StringBuilder builder = new StringBuilder(bytes.length * 2);
277         for (final byte b : bytes) {
278             builder.append(HEX_CHARS[(b >> 4) & 0xF]);
279             builder.append(HEX_CHARS[b & 0xF]);
280         }
281         return builder.toString();
282     }
283 
284     /**
285      * Uses the provided alphabet to convert the character to a set of bits.
286      * 
287      * @param alphabet
288      *            The alphabet for the conversion.
289      * @param c
290      *            The character to convert.
291      * @return The bits for the character from the alphabet.
292      * @throws IllegalArgumentException
293      *             If the character is not in the alphabet.
294      */
295     private static int alphabetToBits(final byte[] alphabet, final char c) {
296         int v = -1;
297         if (c < alphabet.length) {
298             v = alphabet[c];
299         }
300         if (v < 0) {
301             throw new IllegalArgumentException(
302                     "Invalid character in the encoded string: '" + c + "'.");
303         }
304         return v;
305     }
306 
307     /**
308      * Stop creation of a new IOUtils.
309      */
310     private IOUtils() {
311         // Nothing.
312     }
313 }