Coverage Report - com.allanbank.mongodb.util.IOUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
IOUtils
98%
114/116
100%
34/34
3.625
 
 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  1
     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  1
     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  1
     private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
 61  
 
 62  
     /** The logger for the {@link IOUtils}. */
 63  1
     private static final Log LOG = LogFactory.getLog(IOUtils.class);
 64  
 
 65  
     static {
 66  1
         CHAR_TO_HEX_NIBBLE = new byte[128];
 67  1
         Arrays.fill(CHAR_TO_HEX_NIBBLE, (byte) -1);
 68  1
         CHAR_TO_HEX_NIBBLE['0'] = 0;
 69  1
         CHAR_TO_HEX_NIBBLE['1'] = 1;
 70  1
         CHAR_TO_HEX_NIBBLE['2'] = 2;
 71  1
         CHAR_TO_HEX_NIBBLE['3'] = 3;
 72  1
         CHAR_TO_HEX_NIBBLE['4'] = 4;
 73  1
         CHAR_TO_HEX_NIBBLE['5'] = 5;
 74  1
         CHAR_TO_HEX_NIBBLE['6'] = 6;
 75  1
         CHAR_TO_HEX_NIBBLE['7'] = 7;
 76  1
         CHAR_TO_HEX_NIBBLE['8'] = 8;
 77  1
         CHAR_TO_HEX_NIBBLE['9'] = 9;
 78  1
         CHAR_TO_HEX_NIBBLE['a'] = 0xa;
 79  1
         CHAR_TO_HEX_NIBBLE['b'] = 0xb;
 80  1
         CHAR_TO_HEX_NIBBLE['c'] = 0xc;
 81  1
         CHAR_TO_HEX_NIBBLE['d'] = 0xd;
 82  1
         CHAR_TO_HEX_NIBBLE['e'] = 0xe;
 83  1
         CHAR_TO_HEX_NIBBLE['f'] = 0xf;
 84  1
         CHAR_TO_HEX_NIBBLE['A'] = 0xA;
 85  1
         CHAR_TO_HEX_NIBBLE['B'] = 0xB;
 86  1
         CHAR_TO_HEX_NIBBLE['C'] = 0xC;
 87  1
         CHAR_TO_HEX_NIBBLE['D'] = 0xD;
 88  1
         CHAR_TO_HEX_NIBBLE['E'] = 0xE;
 89  1
         CHAR_TO_HEX_NIBBLE['F'] = 0xF;
 90  1
     }
 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  17
         final int base64Length = base64.length();
 101  17
         final int numGroups = base64Length / 4;
 102  17
         if ((4 * numGroups) != base64Length) {
 103  1
             throw new IllegalArgumentException(
 104  
                     "String length must be a multiple of four.");
 105  
         }
 106  
 
 107  16
         int missingBytesInLastGroup = 0;
 108  16
         int numFullGroups = numGroups;
 109  16
         if (base64Length != 0) {
 110  15
             if (base64.charAt(base64Length - 1) == '=') {
 111  14
                 missingBytesInLastGroup++;
 112  14
                 numFullGroups--;
 113  
             }
 114  15
             if (base64.charAt(base64Length - 2) == '=') {
 115  13
                 missingBytesInLastGroup++;
 116  
             }
 117  
         }
 118  16
         final byte[] result = new byte[(3 * numGroups)
 119  
                 - missingBytesInLastGroup];
 120  
 
 121  
         // Translate all 4 character groups from base64 to byte array elements
 122  16
         int base64Index = 0;
 123  16
         int resultIndex = 0;
 124  222
         for (int i = 0; i < numFullGroups; i++) {
 125  207
             final int b1 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 126  
                     base64.charAt(base64Index++));
 127  207
             final int b2 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 128  
                     base64.charAt(base64Index++));
 129  207
             final int b3 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 130  
                     base64.charAt(base64Index++));
 131  207
             final int b4 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 132  
                     base64.charAt(base64Index++));
 133  206
             result[resultIndex++] = (byte) ((b1 << 2) + (b2 >> 4));
 134  206
             result[resultIndex++] = (byte) ((b2 << 4) + (b3 >> 2));
 135  206
             result[resultIndex++] = (byte) ((b3 << 6) + b4);
 136  
         }
 137  
 
 138  
         // Translate partial group, if present
 139  15
         if (missingBytesInLastGroup != 0) {
 140  13
             final int b1 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 141  
                     base64.charAt(base64Index++));
 142  13
             final int b2 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 143  
                     base64.charAt(base64Index++));
 144  13
             result[resultIndex++] = (byte) ((b1 << 2) + (b2 >> 4));
 145  
 
 146  13
             if (missingBytesInLastGroup == 1) {
 147  1
                 final int b3 = alphabetToBits(CHAR_TO_BASE_64_BITS,
 148  
                         base64.charAt(base64Index++));
 149  1
                 result[resultIndex++] = (byte) ((b2 << 4) + (b3 >> 2));
 150  
             }
 151  
         }
 152  
 
 153  15
         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  893
         if (closeable != null) {
 164  855
             close(closeable, Level.FINE, "I/O Exception closing: "
 165  
                     + closeable.getClass().getSimpleName());
 166  
         }
 167  892
     }
 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  924
         if (closeable != null) {
 182  
             try {
 183  900
                 closeable.close();
 184  
             }
 185  1
             catch (final IOException ignored) {
 186  1
                 LOG.log(level, message);
 187  899
             }
 188  
         }
 189  924
     }
 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  76
         final String trimmed = hex.trim();
 200  
 
 201  76
         final int length = trimmed.length();
 202  76
         if ((length & 1) == 1) {
 203  1
             throw new IllegalArgumentException(
 204  
                     "A hex string must be an even number of characters: '"
 205  
                             + trimmed + "'");
 206  
         }
 207  
 
 208  75
         final byte[] bytes = new byte[length >> 1];
 209  325
         for (int i = 0; i < length; i += 2) {
 210  
 
 211  255
             final int v1 = alphabetToBits(CHAR_TO_HEX_NIBBLE, trimmed.charAt(i));
 212  252
             final int v2 = alphabetToBits(CHAR_TO_HEX_NIBBLE,
 213  
                     trimmed.charAt(i + 1));
 214  
 
 215  250
             bytes[i >> 1] = (byte) (((v1 << 4) & 0xF0) + (v2 & 0x0F));
 216  
         }
 217  
 
 218  70
         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  44
         final int length = bytes.length;
 230  
 
 231  
         // Create a buffer with the maximum possible length.
 232  44
         final StringBuffer result = new StringBuffer(4 * ((length + 2) / 3));
 233  
 
 234  
         // Handle each 3 byte group.
 235  44
         int index = 0;
 236  44
         final int numGroups = length / 3;
 237  56174
         for (int i = 0; i < numGroups; i++) {
 238  56130
             final int byte0 = bytes[index++] & 0xff;
 239  56130
             final int byte1 = bytes[index++] & 0xff;
 240  56130
             final int byte2 = bytes[index++] & 0xff;
 241  56130
             result.append(BASE_64_CHARS[byte0 >> 2]);
 242  56130
             result.append(BASE_64_CHARS[((byte0 << 4) & 0x3f) | (byte1 >> 4)]);
 243  56130
             result.append(BASE_64_CHARS[((byte1 << 2) & 0x3f) | (byte2 >> 6)]);
 244  56130
             result.append(BASE_64_CHARS[byte2 & 0x3f]);
 245  
         }
 246  
 
 247  
         // Partial group with padding.
 248  44
         final int numBytesInLastGroup = length - (3 * numGroups);
 249  44
         if (numBytesInLastGroup > 0) {
 250  29
             final int byte0 = bytes[index++] & 0xff;
 251  29
             result.append(BASE_64_CHARS[byte0 >> 2]);
 252  29
             if (numBytesInLastGroup == 1) {
 253  17
                 result.append(BASE_64_CHARS[(byte0 << 4) & 0x3f]);
 254  17
                 result.append("==");
 255  
             }
 256  
             else {
 257  12
                 final int byte1 = bytes[index++] & 0xff;
 258  12
                 result.append(BASE_64_CHARS[((byte0 << 4) & 0x3f)
 259  
                         | (byte1 >> 4)]);
 260  12
                 result.append(BASE_64_CHARS[(byte1 << 2) & 0x3f]);
 261  12
                 result.append('=');
 262  
             }
 263  
         }
 264  
 
 265  44
         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  98
         final StringBuilder builder = new StringBuilder(bytes.length * 2);
 277  1200
         for (final byte b : bytes) {
 278  1102
             builder.append(HEX_CHARS[(b >> 4) & 0xF]);
 279  1102
             builder.append(HEX_CHARS[b & 0xF]);
 280  
         }
 281  98
         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  1362
         int v = -1;
 297  1362
         if (c < alphabet.length) {
 298  1361
             v = alphabet[c];
 299  
         }
 300  1362
         if (v < 0) {
 301  6
             throw new IllegalArgumentException(
 302  
                     "Invalid character in the encoded string: '" + c + "'.");
 303  
         }
 304  1356
         return v;
 305  
     }
 306  
 
 307  
     /**
 308  
      * Stop creation of a new IOUtils.
 309  
      */
 310  0
     private IOUtils() {
 311  
         // Nothing.
 312  0
     }
 313  
 }