Add missing license headers to packetcable-driver gates
[packetcable.git] / packetcable-driver / src / main / java / org / pcmm / gates / impl / SubscriberID.java
1 /*
2  * Copyright (c) 2015 Cable Television Laboratories, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.pcmm.gates.impl;
10
11 import static com.google.common.base.Preconditions.checkNotNull;
12
13 import java.net.Inet4Address;
14 import org.pcmm.base.impl.PCMMBaseObject;
15 import org.pcmm.gates.ISubscriberID;
16
17 import java.net.InetAddress;
18 import java.net.UnknownHostException;
19
20 /**
21  * Implementation of the ISubscriberID interface
22  */
23 public class SubscriberID extends PCMMBaseObject implements ISubscriberID {
24
25     /**
26      * The source IPv4 or IPv6 address
27      */
28     private final InetAddress srcIp;
29
30     /**
31      * Constructor
32      * @param srcIp - the source host address
33      */
34     public SubscriberID(final InetAddress srcIp) {
35         super(SNum.SUBSCRIBER_ID, chooseSType(srcIp));
36         if (srcIp == null) throw new IllegalArgumentException("srcIp must not be null");
37         this.srcIp = srcIp;
38     }
39
40     @Override
41     public InetAddress getSourceIPAddress() {
42         return srcIp;
43     }
44
45     @Override
46     protected byte[] getBytes() {
47         return srcIp.getAddress();
48     }
49
50     @Override
51     public boolean equals(final Object o) {
52         if (this == o) {
53             return true;
54         }
55         if (!(o instanceof SubscriberID)) {
56             return false;
57         }
58         if (!super.equals(o)) {
59             return false;
60         }
61         final SubscriberID that = (SubscriberID) o;
62         return srcIp.equals(that.srcIp);
63     }
64
65     @Override
66     public int hashCode() {
67         int result = super.hashCode();
68         result = 31 * result + srcIp.hashCode();
69         return result;
70     }
71
72     private static byte chooseSType(final InetAddress srcIp) {
73         checkNotNull(srcIp);
74         if (srcIp instanceof Inet4Address) {
75             return STYPE_IPV4;
76         }
77         else {
78             return STYPE_IPV6;
79         }
80     }
81
82     /**
83      * Returns a SubscriberID object from a byte array
84      * @param data - the data to parse
85      * @return - the object or null if cannot be parsed
86      * TODO - make me more robust as RuntimeExceptions can be thrown here.
87      */
88     public static SubscriberID parse(final byte[] data) {
89         try {
90             return new SubscriberID(InetAddress.getByAddress(data));
91         } catch (UnknownHostException e) {
92             return null;
93         }
94     }
95 }