ISSUE
[controller.git] / opendaylight / sal / api / src / main / java / org / opendaylight / controller / sal / core / Node.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 /**
11  * @file   Node.java
12  *
13  * @brief  Describe a generic network element in multiple SDNs technologies
14  *
15  * Describe a generic network element in multiple SDNs technologies. A
16  * Node is identified by the pair (NodeType, NodeID), the nodetype are
17  * needed in order to further specify the nodeID
18  */
19 package org.opendaylight.controller.sal.core;
20
21 import java.io.Serializable;
22 import java.math.BigInteger;
23 import java.util.Set;
24 import java.util.UUID;
25 import java.util.concurrent.ConcurrentHashMap;
26
27 import javax.xml.bind.annotation.XmlAccessType;
28 import javax.xml.bind.annotation.XmlAccessorType;
29 import javax.xml.bind.annotation.XmlAttribute;
30
31 import org.apache.commons.lang3.builder.EqualsBuilder;
32 import org.apache.commons.lang3.builder.HashCodeBuilder;
33 import org.opendaylight.controller.sal.utils.HexEncode;
34
35 /**
36  * Describe a generic network element in multiple SDNs technologies. A
37  * Node is identified by the pair (NodeType, NodeID), the nodetype are
38  * needed in order to further specify the nodeID
39  *
40  */
41 @XmlAccessorType(XmlAccessType.NONE)
42 public class Node implements Serializable {
43     private static final long serialVersionUID = 1L;
44
45     /**
46      * Enum-like static class created with the purpose of identifing
47      * multiple type of nodes in the SDN network. The type is
48      * necessary to figure out to later on correctly use the
49      * nodeID. Using a static class instead of an Enum so we can add
50      * dynamically new types without changing anything in the
51      * surround.
52      */
53     public static final class NodeIDType {
54         private static final ConcurrentHashMap<String, Class> compatibleType =
55             new ConcurrentHashMap<String, Class>();
56         /**
57          * Identifier for an OpenFlow node
58          */
59         public static String OPENFLOW = "OF";
60         /**
61          * Identifier for a PCEP node
62          */
63         public static String PCEP = "PE";
64         /**
65          * Identifier for a ONEPK node
66          */
67         public static String ONEPK = "PK";
68         /**
69          * Identifier for a node in a non-SDN network
70          */
71         public static String PRODUCTION = "PR";
72
73         // Pre-populated types, just here for convenience and ease of
74         // unit-testing, but certainly those could live also outside.
75         static {
76             compatibleType.put(OPENFLOW, Long.class);
77             compatibleType.put(PCEP, UUID.class);
78             compatibleType.put(ONEPK, String.class);
79             compatibleType.put(PRODUCTION, String.class);
80         }
81
82         /**
83          * Return the type of the class expected for the
84          * NodeID, it's used for validity check in the constructor
85          *
86          * @param nodeType the type of the node we want to check
87          * compatibility for
88          *
89          * @return The Class which is supposed to instantiate the ID
90          * for the NodeID
91          */
92         public static Class<?> getClassType(String nodeType) {
93             return compatibleType.get(nodeType);
94         }
95
96         /**
97          * Returns all the registered nodeIDTypes currently available
98          *
99          * @return The current registered NodeIDTypes
100          */
101         public static Set<String> values() {
102             return compatibleType.keySet();
103         }
104
105         /**
106          * Register a new ID for which Node can be created
107          *
108          * @param type, the new type being registered
109          * @param compatibleID, the type of class to be accepted as ID
110          *
111          * @return true if registered, false otherwise
112          */
113         public static boolean registerIDType(String type,
114                                              Class compatibleID) {
115             if (compatibleType.get(type) != null) {
116                 return false;
117             }  else {
118                 compatibleType.put(type, compatibleID);
119                 return true;
120             }
121         }
122
123         /**
124          * UNRegister a new ID for which Node can be created
125          *
126          * @param type, the type being UN-registered
127          *
128          */
129         public static void unRegisterIDType(String type) {
130             compatibleType.remove(type);
131         }
132     }
133
134     // This is the identity of the Node a (Type,ID) pair!, the full
135     // essence of this class.
136     private Object nodeID;
137     private String nodeType;
138
139     // Shadow value for unmarshalling
140     private String nodeIDString;
141
142     /**
143      * Private constructor used for JAXB mapping
144      */
145     private Node() {
146         this.nodeID = null;
147         this.nodeType = null;
148         this.nodeIDString = null;
149     }
150
151     /**
152      * Constructor for the Node objects, it validate the input so if
153      * the ID passed is not of the type expected accordingly to the
154      * type an exception is raised.
155      *
156      * @param nodeType Type of the node we are building
157      * @param id ID used by the SDN technology to identify the node
158      *
159      */
160     public Node(String nodeType, Object id) throws ConstructionException {
161         if (NodeIDType.getClassType(nodeType) != null &&
162             NodeIDType.getClassType(nodeType).isInstance(id)) {
163             this.nodeType = nodeType;
164             this.nodeID = id;
165         } else {
166             throw new ConstructionException("Type of incoming object:"
167                                             + id.getClass() + " not compatible with expected type:"
168                                             + NodeIDType.getClassType(nodeType));
169         }
170     }
171
172     /**
173      * Copy Constructor for the Node objects.
174      *
175      * @param src type of nodes to copy from
176      *
177      */
178     public Node(Node src) throws ConstructionException {
179         if (src != null) {
180             this.nodeType = src.getType();
181             // Here we can reference the object because that is
182             // supposed to be an immutable identifier as well like a
183             // UUID/Integer and so on, hence no need to create a copy
184             // of it
185             this.nodeID = src.getID();
186         } else {
187             throw
188                 new ConstructionException("Null incoming object to copy from");
189         }
190     }
191
192     /**
193      * getter for node type
194      *
195      *
196      * @return The node Type for this Node object
197      */
198     @XmlAttribute(name = "type")
199     public String getType() {
200         return this.nodeType;
201     }
202
203     /**
204      * fill the current object from the string parameters passed, will
205      * be only used by JAXB
206      *
207      * @param typeStr string representing the type of the Node
208      * @param IDStr String representation of the ID
209      */
210     private void fillmeFromString(String typeStr, String IDStr) {
211         if (typeStr == null) {
212             return;
213         }
214
215         if (IDStr == null) {
216             return;
217         }
218
219         this.nodeType = typeStr;
220         if (typeStr.equals(NodeIDType.OPENFLOW)) {
221             this.nodeID = Long.valueOf(HexEncode.stringToLong(IDStr));
222         } else if (typeStr.equals(NodeIDType.ONEPK)) {
223             this.nodeID = IDStr;
224         } else if (typeStr.equals(NodeIDType.PCEP)) {
225             this.nodeID = UUID.fromString(IDStr);
226         } else if (typeStr.equals(NodeIDType.PRODUCTION)) {
227             this.nodeID = IDStr;
228         } else {
229             // We need to lookup via OSGi service registry for an
230             // handler for this
231         }
232     }
233
234     /** 
235      * Private setter for nodeType to be called by JAXB not by anyone
236      * else, Node is immutable
237      * 
238      * @param type of node to be set
239      */
240     private void setType(String type) {
241         this.nodeType = type;
242         if (this.nodeIDString != null) {
243             this.fillmeFromString(type, this.nodeIDString);
244         }
245     }
246
247     /**
248      * getter for node ID
249      *
250      *
251      * @return The node ID for this Node object
252      */
253     public Object getID() {
254         return this.nodeID;
255     }
256
257     /**
258      * Getter for the node ID in string format
259      *
260      * @return The nodeID in string format
261      */
262     @XmlAttribute(name = "id")
263     public String getNodeIDString() {
264         if (this.nodeType.equals(NodeIDType.OPENFLOW)) {
265             return HexEncode.longToHexString((Long) this.nodeID);
266         } else {
267             return this.nodeID.toString();
268         }
269     }
270     
271     /** 
272      * private setter to be used by JAXB
273      * 
274      * @param nodeIDString String representation for NodeID
275      */
276     private void setNodeIDString(String nodeIDString) {
277         this.nodeIDString = nodeIDString;
278         if (this.nodeType != null) {
279             this.fillmeFromString(this.nodeType, nodeIDString);
280         }
281     }
282
283     @Override
284     public int hashCode() {
285         return new HashCodeBuilder(163841, 56473)
286             .append(nodeType)
287             .append(nodeID)
288             .hashCode();
289     }
290
291     @Override
292     public boolean equals(Object obj) {
293         if (obj == null) { return false; }
294         if (obj == this) { return true; }
295         if (obj.getClass() != getClass()) {
296             return false;
297         }
298         Node rhs = (Node)obj;
299         return new EqualsBuilder()
300             .append(this.getType(), rhs.getType())
301             .append(this.getID(), rhs.getID())
302             .isEquals();
303     }
304
305     @Override
306     public String toString() {
307         if (this.nodeType.equals(NodeIDType.OPENFLOW)) {
308             return this.nodeType.toString() + "|"
309                 + HexEncode.longToHexString((Long) this.nodeID);
310         } else {
311             return this.nodeType.toString() + "|" + this.nodeID.toString();
312         }
313     }
314
315     /**
316      * Static method to get back a Node from a string
317      *
318      * @param str string formatted in toString mode that can be
319      * converted back to a Node format.
320      *
321      * @return a Node if succed or null if no
322      */
323     public static Node fromString(String str) {
324         if (str == null) {
325             return null;
326         }
327
328         String parts[] = str.split("\\|");
329         if (parts.length != 2) {
330             // Try to guess from a String formatted as a long because
331             // for long time openflow has been prime citizen so lets
332             // keep this legacy for now
333             String numStr = str.toUpperCase();
334
335             Long ofNodeID = null;
336             if (numStr.startsWith("0X")) {
337                 // Try as an hex number
338                 try {
339                     BigInteger b = new BigInteger(
340                         numStr.replaceFirst("0X", ""), 16);
341                     ofNodeID = Long.valueOf(b.longValue());
342                 } catch (Exception ex) {
343                     ofNodeID = null;
344                 }
345             } else {
346                 // Try as a decimal number
347                 try {
348                     BigInteger b = new BigInteger(numStr);
349                     ofNodeID = Long.valueOf(b.longValue());
350                 } catch (Exception ex) {
351                     ofNodeID = null;
352                 }
353             }
354
355             // Startegy #3 parse as HexLong
356             if (ofNodeID == null) {
357                 try {
358                     ofNodeID = Long.valueOf(HexEncode.stringToLong(numStr));
359                 } catch (Exception ex) {
360                     ofNodeID = null;
361                 }
362             }
363
364             // We ran out of ideas ... return null
365             if (ofNodeID == null) {
366                 return null;
367             }
368
369             // Lets return the cooked up NodeID
370             try {
371                 return new Node(NodeIDType.OPENFLOW, ofNodeID);
372             } catch (ConstructionException ex) {
373                 return null;
374             }
375         }
376
377         String typeStr = parts[0];
378         String IDStr = parts[1];
379
380         return fromString(typeStr, IDStr);
381     }
382
383     /**
384      * Static method to get back a Node from a pair of strings, the
385      * first one being the Type representation, the second one being
386      * the ID string representation, expected to be heavily used in
387      * northbound API.
388      *
389      * @param type, the type of the node we are parsing
390      * @param id, the string representation of the node id
391      *
392      * @return a Node if succed or null if no
393      */
394     public static Node fromString(String typeStr, String IDStr) {
395         if (typeStr == null) {
396             return null;
397         }
398
399         if (IDStr == null) {
400             return null;
401         }
402
403         if (typeStr.equals(NodeIDType.OPENFLOW)) {
404             try {
405                 Long ID = Long.valueOf(HexEncode.stringToLong(IDStr));
406                 return new Node(typeStr, ID);
407             } catch (Exception ex) {
408                 return null;
409             }
410         } else if (typeStr.equals(NodeIDType.ONEPK)) {
411             try {
412                 return new Node(typeStr, IDStr);
413             } catch (Exception ex) {
414                 return null;
415             }
416         } else if (typeStr.equals(NodeIDType.PCEP)) {
417             try {
418                 UUID ID = UUID.fromString(IDStr);
419                 return new Node(typeStr, ID);
420             } catch (Exception ex) {
421                 return null;
422             }
423         } else if (typeStr.equals(NodeIDType.PRODUCTION)) {
424             try {
425                 return new Node(typeStr, IDStr);
426             } catch (Exception ex) {
427                 return null;
428             }
429         } else {
430             // We need to lookup via OSGi service registry for an
431             // handler for this
432         }
433         return null;
434     }
435 }