##### Coverage Report - com.ctrip.apollo.core.utils.MachineUtil

Classes in this File | Line Coverage | Branch Coverage | Complexity
MachineUtil |
0% | 0/24
0% | 0/4
| 3.0;3

1 |  |
     package com.ctrip.apollo.core.utils;
2 |  |
3 |  |
     import org.slf4j.Logger;
4 |  |
     import org.slf4j.LoggerFactory;
5 |  |
6 |  |
     import java.net.NetworkInterface;
7 |  |
     import java.nio.BufferUnderflowException;
8 |  |
     import java.nio.ByteBuffer;
9 |  |
     import java.security.SecureRandom;
10 |  |
     import java.util.Enumeration;
11 |  |
12 |  |
     /**
13 |  |
      * @author Jason Song(song_s@ctrip.com)
14 |  |
      */
15 | 0 |
     public class MachineUtil {
16 | 0 |
       private static final Logger logger = LoggerFactory.getLogger(MachineUtil.class);
17 | 0 |
       private static final int MACHINE_IDENTIFIER = createMachineIdentifier();
18 |  |
19 |  |
       public static int getMachineIdentifier() {
20 | 0 |
         return MACHINE_IDENTIFIER;
21 |  |
       }
22 |  |
23 |  |
       /**
24 |  |
        * Get the machine identifier from mac address
25 |  |
        *
26 |  |
        * @see <a href=https://github.com/mongodb/mongo-java-driver/blob/master/bson/src/main/org/bson/types/ObjectId.java>ObjectId.java</a>
27 |  |
        */
28 |  |
       private static int createMachineIdentifier() {
29 |  |
         // build a 2-byte machine piece based on NICs info
30 |  |
         int machinePiece;
31 |  |
         try {
32 | 0 |
           StringBuilder sb = new StringBuilder();
33 | 0 |
           Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
34 | 0 |
           while (e.hasMoreElements()) {
35 | 0 |
             NetworkInterface ni = e.nextElement();
36 | 0 |
             sb.append(ni.toString());
37 | 0 |
             byte[] mac = ni.getHardwareAddress();
38 | 0 |
             if (mac != null) {
39 | 0 |
               ByteBuffer bb = ByteBuffer.wrap(mac);
40 |  |
               try {
41 | 0 |
                 sb.append(bb.getChar());
42 | 0 |
                 sb.append(bb.getChar());
43 | 0 |
                 sb.append(bb.getChar());
44 | 0 |
               } catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
45 |  |
                 // mac with less than 6 bytes. continue
46 | 0 |
               }
47 |  |
             }
48 | 0 |
           }
49 | 0 |
           machinePiece = sb.toString().hashCode();
50 | 0 |
         } catch (Throwable ex) {
51 |  |
           // exception sometimes happens with IBM JVM, use random
52 | 0 |
           machinePiece = (new SecureRandom().nextInt());
53 | 0 |
           logger.warn(
54 |  |
               "Failed to get machine identifier from network interface, using random number instead",
55 |  |
               ex);
56 | 0 |
         }
57 | 0 |
         return machinePiece;
58 |  |
       }
59 |  |
     }