2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.concepts;
10 import java.util.Arrays;
12 import org.opendaylight.protocol.concepts.Identifier;
13 import com.google.common.base.Objects;
14 import com.google.common.base.Objects.ToStringHelper;
17 * Utility class for implementing identifiers. Subclasses need to provide
18 * a byte[] representation of the encapsulated identifier which is unique
19 * in its domain. This class then implements the required interfaces.
21 * @param <T> template parameter reference to subclass
23 public abstract class AbstractIdentifier<T extends AbstractIdentifier<?>> implements Comparable<T>, Identifier {
24 private static final long serialVersionUID = 7024836009610553163L;
27 * Get raw identifier bytes. Override this method to provide the base
28 * class with a raw representation of your identifier. This is then
29 * used in calculations.
31 * @return Bytearray representation of the identifier
33 abstract protected byte[] getBytes();
35 abstract protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper);
38 public int hashCode() {
39 return Arrays.hashCode(this.getBytes());
43 public boolean equals(final Object o) {
49 if (this.getClass().equals(o.getClass())
50 && o instanceof AbstractIdentifier<?>)
51 return Arrays.equals(this.getBytes(),
52 ((AbstractIdentifier<?>) o).getBytes());
57 public int compareTo(final T id) {
58 boolean assignable = this.getClass().isAssignableFrom(id.getClass());
59 if (assignable == false) {
60 throw new IllegalArgumentException("Object " + id + " is not assignable to " + getClass());
63 final byte[] myb = this.getBytes();
64 final byte[] idb = id.getBytes();
66 for (int i = 0; i < idb.length && i < myb.length; ++i) {
68 return myb[i] - idb[i];
71 if (idb.length != myb.length)
72 return myb.length - idb.length;
78 public final String toString() {
79 return addToStringAttributes(Objects.toStringHelper(this)).toString();