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