Merge "Host updates for Topology"
authorAlessandro Boch <aboch@cisco.com>
Mon, 24 Jun 2013 18:09:14 +0000 (18:09 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 24 Jun 2013 18:09:14 +0000 (18:09 +0000)
87 files changed:
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java [new file with mode: 0644]
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/generator/impl/BindingGeneratorImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/main/java/org/opendaylight/controller/sal/binding/yang/types/TypeProviderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GenEnumResolvingTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GeneratedTypesTest.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GeneretedTypesBitsTest.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/simple-bits-demo.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/AbstractBaseType.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/ReferencedTypeImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractGeneratedType.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractTypeMember.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AnnotationTypeBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/ConstantBuilderImpl.java [deleted file]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/ConstantImpl.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/EnumerationBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedPropertyImpl.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedTypeBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/MethodSignatureBuilderImpl.java
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/MethodSignatureImpl.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/test/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AnnotationBuilderTest.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/ClassCodeGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/GeneratorUtil.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/main/java/org/opendaylight/controller/sal/java/api/generator/InterfaceGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/controller/sal/java/api/generator/test/ClassCodeGeneratorTest.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/AccessModifier.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/AnnotationType.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/CodeGenerator.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/ConcreteType.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/Constant.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/Enumeration.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/GeneratedProperty.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/GeneratedTransferObject.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/GeneratedType.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/MethodSignature.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/ParameterizedType.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/Type.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/TypeMember.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/AnnotationTypeBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/ConstantBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/EnumBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/GeneratedPropertyBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/GeneratedTOBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/GeneratedTypeBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/MethodSignatureBuilder.java
opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/TypeMemberBuilder.java [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/ChoiceBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/builder/impl/RpcDefinitionBuilder.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/impl/YangParserImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/impl/YangParserListenerImpl.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/TypeConstraints.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/UnknownBoundaryNumber.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/main/java/org/opendaylight/controller/yang/parser/util/YangModelBuilderUtil.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/YangParserNegativeTest.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/java/org/opendaylight/controller/yang/parser/impl/YangParserTest.java
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/model/testfile1.yang
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/model/testfile2.yang
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/model/testfile3.yang
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/testfile5.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/testfile6.yang [new file with mode: 0644]
opendaylight/sal/yang-prototype/yang/yang-model-api/src/main/java/org/opendaylight/controller/yang/model/api/ChoiceNode.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/AbstractUnsignedInteger.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/Uint16.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/Uint32.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/Uint64.java
opendaylight/sal/yang-prototype/yang/yang-model-util/src/main/java/org/opendaylight/controller/yang/model/util/Uint8.java
opendaylight/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java [moved from opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUser.java with 94% similarity]
opendaylight/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java [moved from opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/AuthenticatedUserTest.java with 95% similarity]
opendaylight/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManagerImpl.java
opendaylight/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java
opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java
opendaylight/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java
opendaylight/web/devices/src/main/resources/js/page.js
opendaylight/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java
opendaylight/web/flows/src/main/resources/js/page.js
opendaylight/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java
opendaylight/web/topology/src/main/java/org/opendaylight/controller/topology/web/Topology.java
opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/Troubleshoot.java
opendaylight/web/troubleshoot/src/main/java/org/opendaylight/controller/troubleshoot/web/TroubleshootingJsonBean.java

index 63babe7d0a0399ba3e5b9752b5a87740d3f712b7..fb9662366f455f98429e7647044d79caa2bc6417 100644 (file)
@@ -9,10 +9,12 @@
 
 package org.opendaylight.controller.sal.authorization;
 
+import java.io.Serializable;
+
 /**
  * It represents the group/resource access privilege
  */
-public enum Privilege {
+public enum Privilege implements Serializable {
     NONE(""), // no privilege
     READ("r"), // read only
     USE("u"), // use
index 00a2f57308d57e1d76c8f0e88aeb86d74a3f910a..4dcf2b3c3764790e3aab70da16512573b8c3975a 100644 (file)
@@ -225,13 +225,14 @@ public class Match implements Cloneable, Serializable {
         Match reverse = this.clone();
 
         // Flip symmetric fields
-        for (Map.Entry<MatchType, MatchType> entry : Match.reversableMatches
-                .entrySet()) {
+        for (Map.Entry<MatchType, MatchType> entry : Match.reversableMatches.entrySet()) {
             MatchType from = entry.getKey();
             MatchType to = entry.getValue();
             if (this.isPresent(from)) {
-                reverse.setField(to, this.getField(from).getValue(), this
-                        .getField(from).getMask());
+                reverse.setField(to, this.getField(from).getValue(), this.getField(from).getMask());
+                if (!this.isPresent(to)) {
+                    reverse.clearField(from);
+                }
             }
         }
 
index c3982ae08e280dc1fd45b70896934791cfe7f092..5bf57a55c390da3dbf64fdbf2b6b9de9cf3bcb0d 100644 (file)
@@ -255,7 +255,7 @@ public abstract class BitBufferHelper {
             // Now adding the rest of the bits if any
             if (extranumBits != 0) {
                 if (extranumBits < (NetUtils.NumBitsInAByte - extraOffsetBits)) {
-                    valfromnext = (byte) (data[startByteOffset + i + 1] & ((getMSBMask(extranumBits)) >> extraOffsetBits));
+                    valfromnext = (byte) (data[startByteOffset + i] & ((getMSBMask(extranumBits)) >> extraOffsetBits));
                     bytes[i] = (byte) (valfromnext << extraOffsetBits);
                 } else if (extranumBits == (NetUtils.NumBitsInAByte - extraOffsetBits)) {
                     valfromcurr = (data[startByteOffset + i])
index c96e90156178803f7d835f5369a6892054cbcc39..7f151c9502d22f936f2dbb25f24cda9fcdb14585 100644 (file)
@@ -33,6 +33,10 @@ public class Ethernet extends Packet {
         etherTypeClassMap.put(EtherTypes.ARP.shortValue(), ARP.class);
         etherTypeClassMap.put(EtherTypes.IPv4.shortValue(), IPv4.class);
         etherTypeClassMap.put(EtherTypes.LLDP.shortValue(), LLDP.class);
+        etherTypeClassMap.put(EtherTypes.VLANTAGGED.shortValue(), IEEE8021Q.class);
+        etherTypeClassMap.put(EtherTypes.OLDQINQ.shortValue(), IEEE8021Q.class);
+        etherTypeClassMap.put(EtherTypes.QINQ.shortValue(), IEEE8021Q.class);
+        etherTypeClassMap.put(EtherTypes.CISCOQINQ.shortValue(), IEEE8021Q.class);
     }
     private static Map<String, Pair<Integer, Integer>> fieldCoordinates = new LinkedHashMap<String, Pair<Integer, Integer>>() {
         private static final long serialVersionUID = 1L;
diff --git a/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java b/opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java
new file mode 100644 (file)
index 0000000..39c7d38
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.sal.packet;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+
+/**
+ * Class that represents the IEEE 802.1Q objects
+ */
+public class IEEE8021Q extends Packet {
+    private static final String PCP = "PriorityCodePoint";
+    private static final String CFI = "CanonicalFormatIndicator";
+    private static final String VID = "VlanIdentifier";
+    private static final String ETHT = "EtherType";
+
+    private static Map<String, Pair<Integer, Integer>> fieldCoordinates = new LinkedHashMap<String, Pair<Integer, Integer>>() {
+        private static final long serialVersionUID = 1L;
+        {
+            put(PCP, new ImmutablePair<Integer, Integer>(0, 3));
+            put(CFI, new ImmutablePair<Integer, Integer>(3, 1));
+            put(VID, new ImmutablePair<Integer, Integer>(4, 12));
+            put(ETHT, new ImmutablePair<Integer, Integer>(16, 16));
+        }
+    };
+    private final Map<String, byte[]> fieldValues;
+
+    /**
+     * Default constructor that creates and sets the HashMap
+     */
+    public IEEE8021Q() {
+        super();
+        fieldValues = new HashMap<String, byte[]>();
+        hdrFieldCoordMap = fieldCoordinates;
+        hdrFieldsMap = fieldValues;
+    }
+
+    /**
+     * Constructor that sets the access level for the packet and creates and
+     * sets the HashMap
+     */
+    public IEEE8021Q(boolean writeAccess) {
+        super(writeAccess);
+        fieldValues = new HashMap<String, byte[]>();
+        hdrFieldCoordMap = fieldCoordinates;
+        hdrFieldsMap = fieldValues;
+    }
+
+    @Override
+    /**
+     * Store the value read from data stream in hdrFieldMap
+     */
+    public void setHeaderField(String headerField, byte[] readValue) {
+        if (headerField.equals(ETHT)) {
+            payloadClass = Ethernet.etherTypeClassMap.get(BitBufferHelper.getShort(readValue));
+        }
+        hdrFieldsMap.put(headerField, readValue);
+    }
+
+    /**
+     * Gets the priority code point(PCP) stored
+     *
+     * @return byte - the PCP
+     */
+    public byte getPcp() {
+        return BitBufferHelper.getByte(fieldValues.get(PCP));
+    }
+
+    /**
+     * Gets the canonical format indicator(CFI) stored
+     *
+     * @return byte - the CFI
+     */
+    public byte getCfi() {
+        return BitBufferHelper.getByte(fieldValues.get(CFI));
+    }
+
+    /**
+     * Gets the VLAN identifier(VID) stored
+     *
+     * @return short - the VID
+     */
+    public short getVid() {
+        return BitBufferHelper.getShort(fieldValues.get(VID));
+    }
+
+    /**
+     * Gets the etherType stored
+     *
+     * @return short - the etherType
+     */
+    public short getEtherType() {
+        return BitBufferHelper.getShort(fieldValues.get(ETHT));
+    }
+
+    /**
+     * Sets the priority code point(PCP) for the current IEEE 802.1Q object
+     * instance
+     *
+     * @param byte - the PCP to set
+     */
+    public IEEE8021Q setPcp(byte pcp) {
+        byte[] priorityCodePoint = BitBufferHelper.toByteArray(pcp);
+        fieldValues.put(PCP, priorityCodePoint);
+        return this;
+    }
+
+    /**
+     * Sets the canonical format indicator(CFI) for the current IEEE 802.1Q
+     * object instance
+     *
+     * @param byte - the CFI to set
+     */
+    public IEEE8021Q setCfi(byte cfi) {
+        byte[] canonicalFormatIndicator = BitBufferHelper.toByteArray(cfi);
+        fieldValues.put(CFI, canonicalFormatIndicator);
+        return this;
+    }
+
+    /**
+     * Sets the VLAN identifier(VID) for the current IEEE 802.1Q instance
+     *
+     * @param short - the VID to set
+     */
+    public IEEE8021Q setVid(short vid) {
+        byte[] vlanIdentifier = BitBufferHelper.toByteArray(vid);
+        fieldValues.put(VID, vlanIdentifier);
+        return this;
+    }
+
+    /**
+     * Sets the etherType for the current IEEE 802.1Q object instance
+     *
+     * @param short - the etherType to set
+     */
+    public IEEE8021Q setEtherType(short etherType) {
+        byte[] ethType = BitBufferHelper.toByteArray(etherType);
+        fieldValues.put(ETHT, ethType);
+        return this;
+    }
+
+}
diff --git a/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java b/opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java
new file mode 100644 (file)
index 0000000..a4c6c1f
--- /dev/null
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.sal.packet;
+
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.sal.utils.NetUtils;
+
+public class IEEE8021QTest {
+
+    @Test
+    public void testGetPcp() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        byte pcp[] = { 5 };
+        vlan.hdrFieldsMap.put("PriorityCodePoint", pcp);
+        byte spcp = vlan.getPcp();
+        Assert.assertTrue(spcp == 5);
+    }
+
+    @Test
+    public void testGetCfi() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        byte cfi[] = { 0 };
+        vlan.hdrFieldsMap.put("CanonicalFormatIndicator", cfi);
+        byte scfi = vlan.getCfi();
+        Assert.assertTrue(scfi == 0);
+    }
+
+    @Test
+    public void testGetVid() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        byte vid[] = { (byte) 0xF, (byte) 0xFE }; // 4094
+        vlan.hdrFieldsMap.put("VlanIdentifier", vid);
+        short svid = vlan.getVid();
+        Assert.assertTrue(svid == 4094);
+    }
+
+    @Test
+    public void testGetEthertype() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        byte ethType[] = { 8, 6 };
+        vlan.hdrFieldsMap.put("EtherType", ethType);
+        short etherType = vlan.getEtherType();
+        Assert.assertTrue(etherType == 2054);
+    }
+
+    @Test
+    public void testSetPcp() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        byte pcp = 5;
+        vlan.setPcp(pcp);
+        byte[] bpcp = vlan.hdrFieldsMap.get("PriorityCodePoint");
+        Assert.assertTrue(bpcp[0] == 5);
+    }
+
+    @Test
+    public void testSetCfi() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        byte cfi = 0;
+        vlan.setCfi(cfi);
+        byte[] bcfi = vlan.hdrFieldsMap.get("CanonicalFormatIndicator");
+        Assert.assertTrue(bcfi[0] == 0);
+    }
+
+    @Test
+    public void testSetVid() throws Exception {
+        IEEE8021Q vlan = new IEEE8021Q();
+        short vid = 4094; // 0xFFE
+        vlan.setVid(vid);
+        byte[] bvid = vlan.hdrFieldsMap.get("VlanIdentifier");
+        Assert.assertTrue(bvid[0] == (byte) 0xF);
+        Assert.assertTrue(bvid[1] == (byte) 0xFE);
+    }
+
+    @Test
+    public void testSetEthertype() throws Exception {
+        Ethernet eth = new Ethernet();
+        short ethType = 2054; // 0x806
+        eth.setEtherType(ethType);
+        byte[] etherType = eth.hdrFieldsMap.get("EtherType");
+        Assert.assertTrue(etherType[0] == 8);
+        Assert.assertTrue(etherType[1] == 6);
+    }
+
+    @Test
+    public void testDeserialize() throws Exception {
+        short startOffset, numBits;
+        Ethernet eth = new Ethernet();
+        byte[] data = {
+                (byte) 0xA, (byte) 0xC, (byte) 0xE, (byte) 0x14, (byte) 0x37, (byte) 0x45, // Destination MAC
+                (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F, // Source MAC
+                (byte) 0x81, (byte) 0x00, // EtherType
+                (byte) 0xAF, (byte) 0xFE, // PCP, CFI, VLAN ID
+                8, 6, // EtherType
+                0, 1, // Hardware Type
+                8, 0, // Protocol Type
+                6, // Hardware Address Length
+                4, // Protocol Address Length
+                0, 1, // opCode
+                (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F, // Sender Hardware Address
+                (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0x1, // Sender Protocol Address
+                (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, // Target Hardware Address
+                (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0xFE }; // Target Protocol Address
+
+        startOffset = 0;
+        numBits = (short) (data.length * 8);
+        eth.deserialize(data, startOffset, numBits);
+
+        short etherType = eth.getEtherType();
+        Assert.assertTrue(NetUtils.getUnsignedShort(etherType) == 0x8100);
+
+        IEEE8021Q vlanPacket = (IEEE8021Q) eth.getPayload();
+        Assert.assertTrue(vlanPacket.getCfi() == 0);
+        Assert.assertTrue(vlanPacket.getPcp() == 5);
+        Assert.assertTrue(vlanPacket.getVid() == 4094);
+        Assert.assertTrue(vlanPacket.getEtherType() == 2054); // 0x806
+
+        Packet arpPkt = (vlanPacket).getPayload();
+        Assert.assertTrue(arpPkt instanceof ARP);
+    }
+
+    @Test
+    public void testSerialize() throws Exception {
+        Ethernet eth = new Ethernet();
+
+        byte[] dMac = { (byte) 0xA, (byte) 0xC, (byte) 0xE, (byte) 0x14, (byte) 0x37, (byte) 0x45 };
+        byte[] sMac = { (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F };
+        eth.setDestinationMACAddress(dMac);
+        eth.setSourceMACAddress(sMac);
+        eth.setEtherType((short) 33024);
+
+        IEEE8021Q vlan = new IEEE8021Q();
+        vlan.setCfi((byte) 0x0);
+        vlan.setPcp((byte) 0x5);
+        vlan.setVid((short) 4094);
+        vlan.setEtherType((short) 2054);
+
+        vlan.setParent(eth);
+        eth.setPayload(vlan);
+
+        ARP arp = new ARP();
+        arp.setHardwareType((short) 1);
+        arp.setProtocolType((short) 2048);
+        arp.setHardwareAddressLength((byte) 0x6);
+        arp.setProtocolAddressLength((byte) 0x4);
+        arp.setOpCode((byte) 0x1);
+
+        byte[] senderHardwareAddress = { (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F };
+        byte[] senderProtocolAddress = { (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0x1 };
+        byte[] targetProtocolAddress = { (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0xFE };
+        byte[] targetHardwareAddress = { (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 };
+        arp.setSenderHardwareAddress(senderHardwareAddress);
+        arp.setSenderProtocolAddress(senderProtocolAddress);
+        arp.setTargetHardwareAddress(targetHardwareAddress);
+        arp.setTargetProtocolAddress(targetProtocolAddress);
+
+        arp.setParent(vlan);
+        vlan.setPayload(arp);
+
+        byte[] data = eth.serialize();
+
+        Assert.assertTrue(data[0] == (byte) 0x0A); // Destination MAC
+        Assert.assertTrue(data[1] == (byte) 0x0C);
+        Assert.assertTrue(data[2] == (byte) 0x0E);
+        Assert.assertTrue(data[3] == (byte) 0x14);
+        Assert.assertTrue(data[4] == (byte) 0x37);
+        Assert.assertTrue(data[5] == (byte) 0x45);
+        Assert.assertTrue(data[6] == (byte) 0xA6); // Source MAC
+        Assert.assertTrue(data[7] == (byte) 0xEC);
+        Assert.assertTrue(data[8] == (byte) 0x9C);
+        Assert.assertTrue(data[9] == (byte) 0xAE);
+        Assert.assertTrue(data[10] == (byte) 0xB2);
+        Assert.assertTrue(data[11] == (byte) 0x9F);
+        Assert.assertTrue(data[12] == (byte) 0x81); // EtherType
+        Assert.assertTrue(data[13] == (byte) 0x00);
+        Assert.assertTrue(data[14] == (byte) 0xAF); // PCP, CFI, VLAN ID
+        Assert.assertTrue(data[15] == (byte) 0xFE);
+        Assert.assertTrue(data[16] == (byte) 0x08); // EtherType
+        Assert.assertTrue(data[17] == (byte) 0x06);
+        Assert.assertTrue(data[18] == (byte) 0x00); // Hardware Type
+        Assert.assertTrue(data[19] == (byte) 0x01);
+        Assert.assertTrue(data[20] == (byte) 0x08); // Protocol Type
+        Assert.assertTrue(data[21] == (byte) 0x0);
+        Assert.assertTrue(data[22] == (byte) 0x6); // Hardware Address Length
+        Assert.assertTrue(data[23] == (byte) 0x4); // Protocol Address Length
+        Assert.assertTrue(data[24] == (byte) 0x0); // opCode
+        Assert.assertTrue(data[25] == (byte) 0x1); // opCode
+        Assert.assertTrue(data[26] == (byte) 0xA6); // Source MAC
+        Assert.assertTrue(data[27] == (byte) 0xEC);
+        Assert.assertTrue(data[28] == (byte) 0x9C);
+        Assert.assertTrue(data[29] == (byte) 0xAE);
+        Assert.assertTrue(data[30] == (byte) 0xB2);
+        Assert.assertTrue(data[31] == (byte) 0x9F);
+        Assert.assertTrue(data[32] == (byte) 0x09); // Sender Protocol Address
+        Assert.assertTrue(data[33] == (byte) 0x09);
+        Assert.assertTrue(data[34] == (byte) 0x09);
+        Assert.assertTrue(data[35] == (byte) 0x01); // Target Hardware Address
+        Assert.assertTrue(data[36] == (byte) 0x00);
+        Assert.assertTrue(data[37] == (byte) 0x00);
+        Assert.assertTrue(data[38] == (byte) 0x00);
+        Assert.assertTrue(data[39] == (byte) 0x00);
+        Assert.assertTrue(data[40] == (byte) 0x00);
+        Assert.assertTrue(data[41] == (byte) 0x00);
+        Assert.assertTrue(data[42] == (byte) 0x09); // Target Protocol Address
+        Assert.assertTrue(data[43] == (byte) 0x09);
+        Assert.assertTrue(data[44] == (byte) 0x09);
+        Assert.assertTrue(data[45] == (byte) 0xFE);
+    }
+}
index b89dbb44ac786756b60d866c02459097bbe615b4..2235bfb2a32c7dd3fa75b887939af0e428b99827 100644 (file)
@@ -334,7 +334,7 @@ public final class BindingGeneratorImpl implements BindingGenerator {
 
                 final Type rpcRes = Types.parameterizedTypeFor(
                         Types.typeForClass(RpcResult.class), outTypeInstance);
-                method.addReturnType(Types.parameterizedTypeFor(future, rpcRes));
+                method.setReturnType(Types.parameterizedTypeFor(future, rpcRes));
                 for (DataNodeIterator it : rpcInOut) {
                     List<ContainerSchemaNode> nContainers = it.allContainers();
                     if ((nContainers != null) && !nContainers.isEmpty()) {
@@ -446,16 +446,16 @@ public final class BindingGeneratorImpl implements BindingGenerator {
 
             GeneratedTransferObject gto = new GeneratedTOBuilderImpl(
                     returnTypePkgName, returnTypeName).toInstance();
-            newType.addExtendsType(gto);
+            newType.setExtendsType(gto);
         } else {
-            newType.addExtendsType(Types.getBaseIdentityTO());
+            newType.setExtendsType(Types.getBaseIdentityTO());
         }
-
-        return newType.toIdentityInstance();
+        newType.setAbstract(true);
+        return newType.toInstance();
     }
 
     private List<Type> allGroupingsToGenTypes(Module module) {
-        final List<Type> genTypes = new ArrayList<Type>();
+        final List<Type> genTypes = new ArrayList<>();
         final String basePackageName = moduleNamespaceToPackageName(module);
         Set<GroupingDefinition> groupings = module.getGroupings();
         if (groupings != null && !groupings.isEmpty()) {
@@ -804,8 +804,8 @@ public final class BindingGeneratorImpl implements BindingGenerator {
                             .addProperty(parseToClassName(leafName));
 
                     propBuilder.setReadOnly(isReadOnly);
-                    propBuilder.addReturnType(returnType);
-                    propBuilder.addComment(leafDesc);
+                    propBuilder.setReturnType(returnType);
+                    propBuilder.setComment(leafDesc);
 
                     toBuilder.addEqualsIdentity(propBuilder);
                     toBuilder.addHashIdentity(propBuilder);
@@ -946,8 +946,8 @@ public final class BindingGeneratorImpl implements BindingGenerator {
         final MethodSignatureBuilder getMethod = interfaceBuilder
                 .addMethod(getterMethodName(schemaNodeName));
 
-        getMethod.addComment(comment);
-        getMethod.addReturnType(returnType);
+        getMethod.setComment(comment);
+        getMethod.setReturnType(returnType);
 
         return getMethod;
     }
@@ -959,10 +959,10 @@ public final class BindingGeneratorImpl implements BindingGenerator {
         final MethodSignatureBuilder setMethod = interfaceBuilder
                 .addMethod(setterMethodName(schemaNodeName));
 
-        setMethod.addComment(comment);
+        setMethod.setComment(comment);
         setMethod.addParameter(parameterType,
                 parseToValidParamName(schemaNodeName));
-        setMethod.addReturnType(Types.voidType());
+        setMethod.setReturnType(Types.voidType());
 
         return setMethod;
     }
index 96069c273c071b96d3594b484055f0c32913a6f1..9410ffe1de5dc9825325bfc97b076aa32f079a94 100644 (file)
@@ -21,11 +21,9 @@ import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedT
 import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
 import org.opendaylight.controller.yang.common.QName;
 import org.opendaylight.controller.yang.model.api.*;
-import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.*;
+import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
 import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
-import org.opendaylight.controller.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.UnionTypeDefinition;
 import org.opendaylight.controller.yang.model.util.ExtendedType;
 
 import java.util.HashMap;
@@ -56,13 +54,13 @@ public final class TypeProviderImpl implements TypeProvider {
     public void putReferencedType(final SchemaPath refTypePath,
                                   final Type refType) {
         if (refTypePath == null) {
-            throw new IllegalArgumentException("Path reference of " +
-                    "Enumeration Type Definition cannot be NULL!");
+            throw new IllegalArgumentException("Path reference of "
+                    "Enumeration Type Definition cannot be NULL!");
         }
 
         if (refType == null) {
-            throw new IllegalArgumentException("Reference to Enumeration " +
-                    "Type cannot be NULL!");
+            throw new IllegalArgumentException("Reference to Enumeration "
+                    "Type cannot be NULL!");
         }
         referencedTypes.put(refTypePath, refType);
     }
@@ -85,16 +83,13 @@ public final class TypeProviderImpl implements TypeProvider {
             final TypeDefinition<?> typeDefinition) {
         Type returnType = null;
         if (typeDefinition == null) {
-            throw new IllegalArgumentException("Type Definition cannot be " +
-                    "NULL!");
+            throw new IllegalArgumentException("Type Definition cannot be NULL!");
         }
         if (typeDefinition.getQName() == null) {
-            throw new IllegalArgumentException("Type Definition cannot have " +
-                    "non specified QName (QName cannot be NULL!)");
+            throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
         }
         if (typeDefinition.getQName().getLocalName() == null) {
-            throw new IllegalArgumentException("Type Definitions Local Name " +
-                    "cannot be NULL!");
+            throw new IllegalArgumentException("Type Definitions Local Name cannot be NULL!");
         }
         final String typedefName = typeDefinition.getQName().getLocalName();
         if (typeDefinition instanceof ExtendedType) {
@@ -104,15 +99,15 @@ public final class TypeProviderImpl implements TypeProvider {
                 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) baseTypeDef;
                 returnType = provideTypeForLeafref(leafref);
             } else if (baseTypeDef instanceof IdentityrefTypeDefinition) {
-                final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition)typeDefinition;
+                final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) baseTypeDef;
                 returnType = returnTypeForIdentityref(idref);
             } else if (baseTypeDef instanceof EnumTypeDefinition) {
                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
                 returnType = resolveEnumFromTypeDefinition(enumTypeDef,
                         typedefName);
             } else {
-                final Module module = findParentModuleForTypeDefinition(schemaContext,
-                        typeDefinition);
+                final Module module = findParentModuleForTypeDefinition(
+                        schemaContext, typeDefinition);
                 if (module != null) {
                     final Map<String, Type> genTOs = genTypeDefsContextMap
                             .get(module.getName());
@@ -130,32 +125,32 @@ public final class TypeProviderImpl implements TypeProvider {
                 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
                 returnType = provideTypeForLeafref(leafref);
             } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
-                final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition)typeDefinition;
+                final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
                 returnType = returnTypeForIdentityref(idref);
             } else {
                 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
                         .javaTypeForSchemaDefinitionType(typeDefinition);
             }
         }
-        //TODO: add throw exception when we will be able to resolve ALL yang
+        // TODO: add throw exception when we will be able to resolve ALL yang
         // types!
-//        if (returnType == null) {
-//            throw new IllegalArgumentException("Type Provider can't resolve " +
-//                    "type for specified Type Definition " + typedefName);
-//        }
+        // if (returnType == null) {
+        // throw new IllegalArgumentException("Type Provider can't resolve " +
+        // "type for specified Type Definition " + typedefName);
+        // }
         return returnType;
     }
-    
+
     private Type returnTypeForIdentityref(IdentityrefTypeDefinition idref) {
         QName baseIdQName = idref.getIdentity();
         Module module = schemaContext.findModuleByNamespace(baseIdQName.getNamespace());
         IdentitySchemaNode identity = null;
-        for(IdentitySchemaNode id : module.getIdentities()) {
-            if(id.getQName().equals(baseIdQName)) {
+        for (IdentitySchemaNode id : module.getIdentities()) {
+            if (id.getQName().equals(baseIdQName)) {
                 identity = id;
             }
         }
-        if(identity == null) {
+        if (identity == null) {
             throw new IllegalArgumentException("Target identity '" + baseIdQName + "' do not exists");
         }
 
@@ -173,16 +168,13 @@ public final class TypeProviderImpl implements TypeProvider {
             final TypeDefinition<?> typeDefinition) {
         Type returnType = null;
         if (typeDefinition == null) {
-            throw new IllegalArgumentException("Type Definition cannot be " +
-                    "NULL!");
+            throw new IllegalArgumentException("Type Definition cannot be NULL!");
         }
         if (typeDefinition.getQName() == null) {
-            throw new IllegalArgumentException("Type Definition cannot have " +
-                    "non specified QName (QName cannot be NULL!)");
+            throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
         }
         if (typeDefinition.getQName() == null) {
-            throw new IllegalArgumentException("Type Definitions Local Name " +
-                    "cannot be NULL!");
+            throw new IllegalArgumentException("Type Definitions Local Name cannot be NULL!");
         }
 
         final String typedefName = typeDefinition.getQName().getLocalName();
@@ -191,8 +183,8 @@ public final class TypeProviderImpl implements TypeProvider {
 
             if (!(baseTypeDef instanceof LeafrefTypeDefinition)
                     && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
-                final Module module = findParentModuleForTypeDefinition(schemaContext,
-                        typeDefinition);
+                final Module module = findParentModuleForTypeDefinition(
+                        schemaContext, typeDefinition);
 
                 if (module != null) {
                     final Map<String, Type> genTOs = genTypeDefsContextMap
@@ -209,8 +201,7 @@ public final class TypeProviderImpl implements TypeProvider {
     private TypeDefinition<?> baseTypeDefForExtendedType(
             final TypeDefinition<?> extendTypeDef) {
         if (extendTypeDef == null) {
-            throw new IllegalArgumentException("Type Definiition reference " +
-                    "cannot be NULL!");
+            throw new IllegalArgumentException("Type Definiition reference cannot be NULL!");
         }
         final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
         if (baseTypeDef instanceof ExtendedType) {
@@ -224,13 +215,11 @@ public final class TypeProviderImpl implements TypeProvider {
     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType) {
         Type returnType = null;
         if (leafrefType == null) {
-            throw new IllegalArgumentException("Leafref Type Definition " +
-                    "reference cannot be NULL!");
+            throw new IllegalArgumentException("Leafref Type Definition reference cannot be NULL!");
         }
 
         if (leafrefType.getPathStatement() == null) {
-            throw new IllegalArgumentException("The Path Statement for " +
-                    "Leafref Type Definition cannot be NULL!");
+            throw new IllegalArgumentException("The Path Statement for Leafref Type Definition cannot be NULL!");
         }
 
         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
@@ -240,22 +229,23 @@ public final class TypeProviderImpl implements TypeProvider {
             if (strXPath.matches(".*//[.* | .*//].*")) {
                 returnType = Types.typeForClass(Object.class);
             } else {
-                final Module module = findParentModuleForTypeDefinition(schemaContext, leafrefType);
+                final Module module = findParentModuleForTypeDefinition(
+                        schemaContext, leafrefType);
                 if (module != null) {
                     final DataSchemaNode dataNode;
                     if (xpath.isAbsolute()) {
                         dataNode = findDataSchemaNode(schemaContext, module,
                                 xpath);
                     } else {
-                        dataNode = findDataSchemaNodeForRelativeXPath(schemaContext,
-                                module, leafrefType, xpath);
+                        dataNode = findDataSchemaNodeForRelativeXPath(
+                                schemaContext, module, leafrefType, xpath);
                     }
 
                     if (leafContainsEnumDefinition(dataNode)) {
                         returnType = referencedTypes.get(dataNode.getPath());
                     } else if (leafListContainsEnumDefinition(dataNode)) {
-                        returnType = Types.listTypeFor(referencedTypes.get(
-                                dataNode.getPath()));
+                        returnType = Types.listTypeFor(referencedTypes
+                                .get(dataNode.getPath()));
                     } else {
                         returnType = resolveTypeFromDataSchemaNode(dataNode);
                     }
@@ -275,8 +265,7 @@ public final class TypeProviderImpl implements TypeProvider {
         return false;
     }
 
-    private boolean leafListContainsEnumDefinition(
-            final DataSchemaNode dataNode) {
+    private boolean leafListContainsEnumDefinition(final DataSchemaNode dataNode) {
         if (dataNode instanceof LeafListSchemaNode) {
             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
             if (leafList.getType() instanceof EnumTypeDefinition) {
@@ -289,25 +278,22 @@ public final class TypeProviderImpl implements TypeProvider {
     private Enumeration resolveEnumFromTypeDefinition(
             final EnumTypeDefinition enumTypeDef, final String enumName) {
         if (enumTypeDef == null) {
-            throw new IllegalArgumentException("EnumTypeDefinition reference " +
-                    "cannot be NULL!");
+            throw new IllegalArgumentException("EnumTypeDefinition reference cannot be NULL!");
         }
         if (enumTypeDef.getValues() == null) {
-            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
-                    "contain at least ONE value definition!");
+            throw new IllegalArgumentException("EnumTypeDefinition MUST contain at least ONE value definition!");
         }
         if (enumTypeDef.getQName() == null) {
-            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
-                    "contain NON-NULL QName!");
+            throw new IllegalArgumentException("EnumTypeDefinition MUST contain NON-NULL QName!");
         }
         if (enumTypeDef.getQName().getLocalName() == null) {
-            throw new IllegalArgumentException("Local Name in " +
-                    "EnumTypeDefinition QName cannot be NULL!");
+            throw new IllegalArgumentException("Local Name in EnumTypeDefinition QName cannot be NULL!");
         }
 
         final String enumerationName = parseToClassName(enumName);
 
-        Module module = findParentModuleForTypeDefinition(schemaContext, enumTypeDef);
+        Module module = findParentModuleForTypeDefinition(schemaContext,
+                enumTypeDef);
         final String basePackageName = moduleNamespaceToPackageName(module);
 
         final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
@@ -320,24 +306,19 @@ public final class TypeProviderImpl implements TypeProvider {
             final EnumTypeDefinition enumTypeDef, final String enumName,
             final GeneratedTypeBuilder typeBuilder) {
         if (enumTypeDef == null) {
-            throw new IllegalArgumentException("EnumTypeDefinition reference " +
-                    "cannot be NULL!");
+            throw new IllegalArgumentException("EnumTypeDefinition reference cannot be NULL!");
         }
         if (enumTypeDef.getValues() == null) {
-            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
-                    "contain at least ONE value definition!");
+            throw new IllegalArgumentException("EnumTypeDefinition MUST contain at least ONE value definition!");
         }
         if (enumTypeDef.getQName() == null) {
-            throw new IllegalArgumentException("EnumTypeDefinition MUST " +
-                    "contain NON-NULL QName!");
+            throw new IllegalArgumentException("EnumTypeDefinition MUST contain NON-NULL QName!");
         }
         if (enumTypeDef.getQName().getLocalName() == null) {
-            throw new IllegalArgumentException("Local Name in " +
-                    "EnumTypeDefinition QName cannot be NULL!");
+            throw new IllegalArgumentException("Local Name in EnumTypeDefinition QName cannot be NULL!");
         }
         if (typeBuilder == null) {
-            throw new IllegalArgumentException("Generated Type Builder " +
-                    "reference cannot be NULL!");
+            throw new IllegalArgumentException("Generated Type Builder reference cannot be NULL!");
         }
 
         final String enumerationName = parseToClassName(enumName);
@@ -350,8 +331,7 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private void updateEnumPairsFromEnumTypeDef(
-            final EnumTypeDefinition enumTypeDef,
-            final EnumBuilder enumBuilder) {
+            final EnumTypeDefinition enumTypeDef, final EnumBuilder enumBuilder) {
         if (enumBuilder != null) {
             final List<EnumPair> enums = enumTypeDef.getValues();
             if (enums != null) {
@@ -390,8 +370,7 @@ public final class TypeProviderImpl implements TypeProvider {
     private void resolveTypeDefsFromContext() {
         final Set<Module> modules = schemaContext.getModules();
         if (modules == null) {
-            throw new IllegalArgumentException("Sef of Modules cannot be " +
-                    "NULL!");
+            throw new IllegalArgumentException("Sef of Modules cannot be NULL!");
         }
         for (final Module module : modules) {
             if (module == null) {
@@ -413,7 +392,8 @@ public final class TypeProviderImpl implements TypeProvider {
                 final List<ExtendedType> extUnions = UnionDependencySort
                         .sort(typeDefinitions);
                 for (final ExtendedType extUnionType : extUnions) {
-                    addUnionGeneratedTypeDefinition(basePackageName, extUnionType);
+                    addUnionGeneratedTypeDefinition(basePackageName,
+                            extUnionType);
                 }
             }
         }
@@ -424,7 +404,6 @@ public final class TypeProviderImpl implements TypeProvider {
         if ((basePackageName != null) && (moduleName != null)
                 && (typedef != null) && (typedef.getQName() != null)) {
 
-
             final String typedefName = typedef.getQName().getLocalName();
             final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
             if (!(baseTypeDefinition instanceof LeafrefTypeDefinition)
@@ -435,6 +414,11 @@ public final class TypeProviderImpl implements TypeProvider {
                     returnType = resolveEnumFromTypeDefinition(enumTypeDef,
                             typedefName);
 
+                } else if (baseTypeDefinition instanceof BitsTypeDefinition) {
+                    final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) baseTypeDefinition;
+                    returnType = bitsTypedefToTransferObject(bitsTypeDefinition,
+                            basePackageName, typedefName);
+
                 } else {
                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
                             .javaTypeForSchemaDefinitionType(baseTypeDefinition);
@@ -443,8 +427,8 @@ public final class TypeProviderImpl implements TypeProvider {
                             javaType);
                 }
                 if (returnType != null) {
-                    final Map<String, Type> typeMap = genTypeDefsContextMap.get
-                            (moduleName);
+                    final Map<String, Type> typeMap = genTypeDefsContextMap
+                            .get(moduleName);
                     if (typeMap != null) {
                         typeMap.put(typedefName, returnType);
                     }
@@ -468,7 +452,7 @@ public final class TypeProviderImpl implements TypeProvider {
             final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
                     .addProperty(propertyName);
 
-            genPropBuilder.addReturnType(javaType);
+            genPropBuilder.setReturnType(javaType);
             genTOBuilder.addEqualsIdentity(genPropBuilder);
             genTOBuilder.addHashIdentity(genPropBuilder);
             genTOBuilder.addToStringProperty(genPropBuilder);
@@ -480,26 +464,22 @@ public final class TypeProviderImpl implements TypeProvider {
     private void addUnionGeneratedTypeDefinition(final String basePackageName,
                                                  final TypeDefinition<?> typedef) {
         if (basePackageName == null) {
-            throw new IllegalArgumentException("Base Package Name cannot be " +
-                    "NULL!");
+            throw new IllegalArgumentException("Base Package Name cannot be NULL!");
         }
         if (typedef == null) {
-            throw new IllegalArgumentException("Type Definition cannot be " +
-                    "NULL!");
+            throw new IllegalArgumentException("Type Definition cannot be NULL!");
         }
         if (typedef.getQName() == null) {
-            throw new IllegalArgumentException("Type Definition cannot have " +
-                    "non specified QName (QName cannot be NULL!)");
+            throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
         }
 
         final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
         if ((baseTypeDefinition != null)
                 && (baseTypeDefinition instanceof UnionTypeDefinition)) {
             final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
-            final List<TypeDefinition<?>> unionTypes = unionTypeDef
-                    .getTypes();
-            final Module parentModule = findParentModuleForTypeDefinition(schemaContext,
-                    typedef);
+            final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
+            final Module parentModule = findParentModuleForTypeDefinition(
+                    schemaContext, typedef);
 
             Map<String, Type> genTOsMap = null;
             if (parentModule != null && parentModule.getName() != null) {
@@ -510,17 +490,17 @@ public final class TypeProviderImpl implements TypeProvider {
                     basePackageName, typedef);
             if ((unionTypes != null) && (unionGenTransObject != null)) {
                 for (final TypeDefinition<?> unionType : unionTypes) {
-                    final String typeName = unionType.getQName()
-                            .getLocalName();
+                    final String typeName = unionType.getQName().getLocalName();
                     if (unionType instanceof ExtendedType) {
-                        final Module unionTypeModule = findParentModuleForTypeDefinition(schemaContext,
-                                unionType);
-                        if (unionTypeModule != null && unionTypeModule.getName() != null) {
+                        final Module unionTypeModule = findParentModuleForTypeDefinition(
+                                schemaContext, unionType);
+                        if (unionTypeModule != null
+                                && unionTypeModule.getName() != null) {
                             final Map<String, Type> innerGenTOs = genTypeDefsContextMap
                                     .get(unionTypeModule.getName());
 
-                            final GeneratedTransferObject genTransferObject =
-                                    (GeneratedTransferObject) innerGenTOs.get(typeName);
+                            final GeneratedTransferObject genTransferObject = (GeneratedTransferObject) innerGenTOs
+                                    .get(typeName);
                             if (genTransferObject != null) {
                                 updateUnionTypeAsProperty(unionGenTransObject,
                                         genTransferObject,
@@ -528,8 +508,7 @@ public final class TypeProviderImpl implements TypeProvider {
                             }
                         }
                     } else if (unionType instanceof EnumTypeDefinition) {
-                        final EnumBuilder
-                                enumBuilder = resolveInnerEnumFromTypeDefinition(
+                        final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(
                                 (EnumTypeDefinition) unionType, typeName,
                                 unionGenTransObject);
                         final Type enumRefType = new ReferencedTypeImpl(
@@ -556,10 +535,9 @@ public final class TypeProviderImpl implements TypeProvider {
             final GeneratedTOBuilder unionGenTransObject, final Type type,
             final String propertyName) {
         if (unionGenTransObject != null && type != null) {
-            final GeneratedPropertyBuilder propBuilder =
-                    unionGenTransObject.addProperty(parseToValidParamName(
-                            propertyName));
-            propBuilder.addReturnType(type);
+            final GeneratedPropertyBuilder propBuilder = unionGenTransObject
+                    .addProperty(parseToValidParamName(propertyName));
+            propBuilder.setReturnType(type);
             propBuilder.setReadOnly(false);
 
             if (!(type instanceof Enumeration)) {
@@ -587,4 +565,35 @@ public final class TypeProviderImpl implements TypeProvider {
         }
         return null;
     }
+
+    private GeneratedTransferObject bitsTypedefToTransferObject(
+            final BitsTypeDefinition bitsTypeDefinition, final String basePackageName, final String typedefName) {
+
+        if (bitsTypeDefinition == null) {
+            throw new IllegalArgumentException("Bits TypeDefinition cannot be NULL!");
+        }
+        if (basePackageName == null) {
+            throw new IllegalArgumentException("Base Package Name cannot be NULL!");
+        }
+        if (typedefName == null) {
+            throw new IllegalArgumentException("Type Definition Local Name cannot be NULL!");
+        }
+
+        final String typeDefName = parseToClassName(typedefName);
+        final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName);
+
+        final List<Bit> bitList = bitsTypeDefinition.getBits();
+        GeneratedPropertyBuilder genPropertyBuilder;
+        for (final Bit bit : bitList) {
+            String name = bit.getName();
+            genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
+            genPropertyBuilder.setReadOnly(false);
+            genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
+
+            genTOBuilder.addEqualsIdentity(genPropertyBuilder);
+            genTOBuilder.addHashIdentity(genPropertyBuilder);
+            genTOBuilder.addToStringProperty(genPropertyBuilder);
+        }
+        return genTOBuilder.toInstance();
+    }
 }
index a95eb072ba4f2bc35329fe5dd121727ccb3f7bcc..10ea9fae1f7ebb7a62ce9e8b1e13b4f54159ed22 100644 (file)
@@ -76,7 +76,7 @@ public class GenEnumResolvingTest {
 
         Enumeration linkUpDownTrapEnable = null;
         Enumeration operStatus = null;
-        final List<Enumeration> enums = genInterface.getEnumDefintions();
+        final List<Enumeration> enums = genInterface.getEnumerations();
         assertNotNull("Generated Type Interface cannot contain NULL reference" +
                 " to Enumeration types!", enums);
         assertEquals("Generated Type Interface MUST contain 2 Enumeration " +
index b226252eaea7a635cace166cb3721f307725058a..cfa74a005f31f12ca157fb0b736f9a0983ca8001 100644 (file)
@@ -16,7 +16,6 @@ import java.util.Set;
 
 import org.junit.Test;
 import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
-import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GeneretedTypesBitsTest.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/java/org/opendaylight/controller/sal/binding/generator/impl/GeneretedTypesBitsTest.java
new file mode 100644 (file)
index 0000000..646efd1
--- /dev/null
@@ -0,0 +1,159 @@
+package org.opendaylight.controller.sal.binding.generator.impl;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature.Parameter;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+public class GeneretedTypesBitsTest {
+
+    private SchemaContext resolveSchemaContextFromFiles(
+            final String... yangFiles) {
+        final YangModelParser parser = new YangParserImpl();
+
+        final List<File> inputFiles = new ArrayList<File>();
+        for (int i = 0; i < yangFiles.length; ++i) {
+            inputFiles.add(new File(yangFiles[i]));
+        }
+
+        final Set<Module> modules = parser.parseYangModels(inputFiles);
+        return parser.resolveSchemaContext(modules);
+    }
+
+    @Test
+    public void testGeneretedTypesBitsTest() {
+        final String yangTypesPath = getClass().getResource(
+                "/simple-bits-demo.yang").getPath();
+
+        final SchemaContext context = resolveSchemaContextFromFiles(yangTypesPath);
+        assertTrue(context != null);
+
+        final BindingGenerator bindingGen = new BindingGeneratorImpl();
+        final List<Type> genTypes = bindingGen.generateTypes(context);
+        assertTrue(genTypes != null);
+
+        List<MethodSignature> methodSignaturesList = null;
+
+        boolean leafParentFound = false;
+
+        boolean byteTypeFound = false;
+        int classPropertiesNumb = 0;
+        int toStringPropertiesNum = 0;
+        int equalPropertiesNum = 0;
+        int hashPropertiesNum = 0;
+
+        String nameReturnParamType = "";
+        String nameMethodeParamType = "";
+        boolean getByteLeafMethodFound = false;
+        boolean setByteLeafMethodFound = false;
+        int setByteLeafMethodParamNum = 0;
+
+        for (final Type type : genTypes) {
+            if (type instanceof GeneratedTransferObject) { // searching for
+                                                            // ByteType
+                final GeneratedTransferObject genTO = (GeneratedTransferObject) type;
+                if (genTO.getName().equals("ByteType")) {
+                    byteTypeFound = true;
+                    List<GeneratedProperty> genProperties = genTO
+                            .getProperties();
+                    classPropertiesNumb = genProperties.size();
+
+                    genProperties = null;
+                    genProperties = genTO.getToStringIdentifiers();
+                    toStringPropertiesNum = genProperties.size();
+
+                    genProperties = null;
+                    genProperties = genTO.getEqualsIdentifiers();
+                    equalPropertiesNum = genProperties.size();
+
+                    genProperties = null;
+                    genProperties = genTO.getHashCodeIdentifiers();
+                    hashPropertiesNum = genProperties.size();
+
+                }
+            } else if (type instanceof GeneratedType) { // searching for
+                                                        // interface
+                                                        // LeafParameterContainer
+                final GeneratedType genType = (GeneratedType) type;
+                if (genType.getName().compareTo("LeafParentContainer") == 0) {
+                    leafParentFound = true;
+                    // check of methods
+                    methodSignaturesList = genType.getMethodDefinitions();
+                    if (methodSignaturesList != null) {
+                        for (MethodSignature methodSignature : methodSignaturesList) { // loop
+                                                                                        // through
+                                                                                        // all
+                                                                                        // methods
+                            if (methodSignature.getName().compareTo(
+                                    "getByteLeaf") == 0) {
+                                getByteLeafMethodFound = true;
+
+                                nameReturnParamType = methodSignature
+                                        .getReturnType().getName();
+                            } else if (methodSignature.getName().compareTo(
+                                    "setByteLeaf") == 0) {
+                                setByteLeafMethodFound = true;
+
+                                List<Parameter> parameters = methodSignature
+                                        .getParameters();
+                                setByteLeafMethodParamNum = parameters.size();
+                                for (Parameter parameter : parameters) {
+                                    nameMethodeParamType = parameter.getType()
+                                            .getName();
+                                }
+
+                            }
+
+                        }
+                    }
+                }
+            }
+
+        }
+
+        assertTrue("type >ByteType< wasn't in YANG file", byteTypeFound == true);
+
+        assertTrue("Incorrect number of bit properties in class",
+                classPropertiesNumb == 8);
+
+        assertTrue("Incorrect number of properties in toString method",
+                toStringPropertiesNum == 8);
+        assertTrue("Incorrect number of properties in equals method",
+                equalPropertiesNum == 8);
+        assertTrue("Incorrect number of properties in hash method",
+                hashPropertiesNum == 8);
+        assertTrue("LeafParameterContainer container wasn't found",
+                leafParentFound == true);
+
+        assertTrue("No methods were generated", methodSignaturesList != null);
+
+        assertTrue("Method getByteLeaf wasn't generated.",
+                getByteLeafMethodFound == true);
+        assertTrue("Wrong returning parameter type of method getByteLeaf",
+                nameReturnParamType.compareTo("ByteType") == 0);
+
+        assertTrue("Method setByteLeaf wasn't generated.",
+                setByteLeafMethodFound == true);
+        assertTrue("Incorrect number of input parameters for setByteLeaf",
+                setByteLeafMethodParamNum == 1);
+        assertTrue("Wrong input parameter type",
+                nameMethodeParamType.compareTo("ByteType") == 0);
+
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/simple-bits-demo.yang b/opendaylight/sal/yang-prototype/code-generator/binding-generator-impl/src/test/resources/simple-bits-demo.yang
new file mode 100644 (file)
index 0000000..d7e69d1
--- /dev/null
@@ -0,0 +1,54 @@
+module simple-bits-demo {
+    
+    namespace "urn:simple:bits:demo";
+    prefix "sbd";
+
+    organization "OPEN DAYLIGHT";
+    contact "http://www.opendaylight.org/";    
+
+    revision 2013-06-11 {
+        
+    }
+
+    typedef byte-type {
+        type bits {
+            bit first-bit {
+                position 10;
+            }
+            bit second-bit {
+                position 20;
+            }
+            bit third-bit {
+                position 30;
+            }
+            bit forth-bit {
+                position 40;
+            }       
+            bit fifth-bit {
+                position 50;
+            }       
+            bit sixth-bit {
+                position 60;
+            }       
+            bit seventh-bit {
+                position 70;
+            }       
+            bit eight-bit {
+                position 80;
+            }       
+            
+    }
+
+    typedef jo {
+        type uint32;
+    }
+
+    
+    container leaf-parent-container {
+        leaf byte-leaf {
+            type byte-type;
+        }
+        
+    }
+
+}
\ No newline at end of file
index a9d1cf5227c4efb575debadfb52eb288f64032b7..a67e4163e9a15694c70584ba6aafd0ba4b319fb2 100644 (file)
@@ -24,6 +24,15 @@ public class AbstractBaseType implements Type {
         return name;\r
     }\r
 \r
+    @Override\r
+    public String getFullyQualifiedName() {\r
+        if (packageName.isEmpty()) {\r
+            return name;\r
+        } else {\r
+            return packageName + "." + name;\r
+        }\r
+    }\r
+\r
     protected AbstractBaseType(String pkName, String name) {\r
         this.packageName = pkName;\r
         this.name = name;\r
@@ -68,5 +77,4 @@ public class AbstractBaseType implements Type {
         }\r
         return "Type (" + packageName + "." + name + ")";\r
     }\r
-\r
 }\r
index 8f265c4ec39a2e7404a957da9e444e4d4dfd5ef5..bffa013f8402038d0ecc67e355b35b862205fc28 100644 (file)
@@ -7,82 +7,19 @@
  */
 package org.opendaylight.controller.binding.generator.util;
 
-import org.opendaylight.controller.sal.binding.model.api.Type;
+public final class ReferencedTypeImpl extends AbstractBaseType {
 
-
-public final class ReferencedTypeImpl implements Type {
-    
-    private final String packageName;
-    private final String name;
-    
     public ReferencedTypeImpl(String packageName, String name) {
-        super();
-        this.packageName = packageName;
-        this.name = name;
-    }
-
-    /* (non-Javadoc)
-     * @see org.opendaylight.controller.sal.binding.model.api.Type#getPackageName()
-     */
-    @Override
-    public String getPackageName() {
-        return packageName;
-    }
-
-    /* (non-Javadoc)
-     * @see org.opendaylight.controller.sal.binding.model.api.Type#getName()
-     */
-    @Override
-    public String getName() {
-        return name;
-    }
-
-    @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
-        result = prime * result
-                + ((packageName == null) ? 0 : packageName.hashCode());
-        return result;
-    }
-
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        ReferencedTypeImpl other = (ReferencedTypeImpl) obj;
-        if (name == null) {
-            if (other.name != null) {
-                return false;
-            }
-        } else if (!name.equals(other.name)) {
-            return false;
-        }
-        if (packageName == null) {
-            if (other.packageName != null) {
-                return false;
-            }
-        } else if (!packageName.equals(other.packageName)) {
-            return false;
-        }
-        return true;
+        super(packageName, name);
     }
 
     @Override
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("ReferencedTypeImpl [packageName=");
-        builder.append(packageName);
+        builder.append(getPackageName());
         builder.append(", name=");
-        builder.append(name);
+        builder.append(getName());
         builder.append("]");
         return builder.toString();
     }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractGeneratedType.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractGeneratedType.java
new file mode 100644 (file)
index 0000000..5609f73
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+
+import org.opendaylight.controller.binding.generator.util.AbstractBaseType;
+import org.opendaylight.controller.sal.binding.model.api.*;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+abstract class AbstractGeneratedType extends AbstractBaseType implements GeneratedType {
+
+    private final Type parent;
+    private final String comment;
+    private final List<AnnotationType> annotations;
+    private final List<Type> implementsTypes;
+    private final List<Enumeration> enumerations;
+    private final List<Constant> constants;
+    private final List<MethodSignature> methodSignatures;
+    private final List<GeneratedType> enclosedTypes;
+    private final boolean isAbstract;
+
+    public AbstractGeneratedType(final Type parent, final String packageName,
+                             final String name, final String comment,
+                             final List<AnnotationTypeBuilder> annotationBuilders,
+                             final boolean isAbstract,
+                             final List<Type> implementsTypes,
+                             final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+                             final List<GeneratedTOBuilder> enclosedGenTOBuilders,
+                             final List<EnumBuilder> enumBuilders,
+                             final List<Constant> constants,
+                             final List<MethodSignatureBuilder> methodBuilders) {
+        super(packageName, name);
+        this.parent = parent;
+        this.comment = comment;
+        this.annotations = toUnmodifiableAnnotations(annotationBuilders);
+        this.implementsTypes = Collections.unmodifiableList(implementsTypes);
+        this.constants = toUnmodifiableConstants(constants);
+        this.enumerations = toUnmodifiableEnumerations(enumBuilders);
+        this.methodSignatures = toUnmodifiableMethods(methodBuilders);
+        this.enclosedTypes = toUnmodifiableEnclosedTypes(enclosedGenTypeBuilders, enclosedGenTOBuilders);
+        this.isAbstract = isAbstract;
+    }
+
+    private List<GeneratedType> toUnmodifiableEnclosedTypes(final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+                                                            final List<GeneratedTOBuilder> enclosedGenTOBuilders) {
+        final List<GeneratedType> enclosedTypes = new ArrayList<>();
+        for (final GeneratedTypeBuilder builder : enclosedGenTypeBuilders) {
+            if (builder != null) {
+                enclosedTypes.add(builder.toInstance());
+            }
+        }
+
+        for (final GeneratedTOBuilder builder : enclosedGenTOBuilders) {
+            if (builder != null) {
+                enclosedTypes.add(builder.toInstance());
+            }
+        }
+        return enclosedTypes;
+    }
+
+    protected List<AnnotationType> toUnmodifiableAnnotations(
+            final List<AnnotationTypeBuilder> annotationBuilders) {
+        final List<AnnotationType> annotations = new ArrayList<>();
+        for (final AnnotationTypeBuilder builder : annotationBuilders) {
+            annotations.add(builder.toInstance());
+        }
+        return Collections.unmodifiableList(annotations);
+    }
+
+    protected List<MethodSignature> toUnmodifiableMethods(
+            List<MethodSignatureBuilder> methodBuilders) {
+        final List<MethodSignature> methods = new ArrayList<>();
+        for (final MethodSignatureBuilder methodBuilder : methodBuilders) {
+            methods.add(methodBuilder.toInstance(this));
+        }
+        return Collections.unmodifiableList(methods);
+    }
+
+    protected List<Enumeration> toUnmodifiableEnumerations(
+            List<EnumBuilder> enumBuilders) {
+        final List<Enumeration> enums = new ArrayList<>();
+        for (final EnumBuilder enumBuilder : enumBuilders) {
+            enums.add(enumBuilder.toInstance(this));
+        }
+        return Collections.unmodifiableList(enums);
+    }
+
+    protected List<Constant> toUnmodifiableConstants(
+            List<Constant> constants) {
+        for (final Constant constant : constants) {
+            constants.add(new ConstantImpl(this, constant.getType(),
+                    constant.getName(), constant.getValue()));
+        }
+        return Collections.unmodifiableList(constants);
+    }
+
+    @Override
+    public Type getParentType() {
+        return parent;
+    }
+
+    @Override
+    public String getComment() {
+        return comment;
+    }
+
+    @Override
+    public List<AnnotationType> getAnnotations() {
+        return annotations;
+    }
+
+    @Override
+    public boolean isAbstract() {
+       return isAbstract;
+    }
+
+     @Override
+    public List<Type> getImplements() {
+        return implementsTypes;
+    }
+
+    @Override
+    public List<GeneratedType> getEnclosedTypes() {
+        return enclosedTypes;
+    }
+
+    @Override
+    public List<Enumeration> getEnumerations() {
+        return enumerations;
+    }
+
+    @Override
+    public List<Constant> getConstantDefinitions() {
+        return constants;
+    }
+
+    @Override
+    public List<MethodSignature> getMethodDefinitions() {
+        return methodSignatures;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("GeneratedType [packageName=");
+        builder.append(getPackageName());
+        builder.append(", name=");
+        builder.append(getName());
+        if (parent != null) {
+            builder.append(", parent=");
+            builder.append(parent.getFullyQualifiedName());
+        } else {
+            builder.append(", parent=null");
+        }
+        builder.append(", comment=");
+        builder.append(comment);
+        builder.append(", annotations=");
+        builder.append(annotations);
+        builder.append(", enclosedTypes=");
+        builder.append(enclosedTypes);
+        builder.append(", enumerations=");
+        builder.append(enumerations);
+        builder.append(", constants=");
+        builder.append(constants);
+        builder.append(", methodSignatures=");
+        builder.append(methodSignatures);
+        builder.append("]");
+        return builder.toString();
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java
new file mode 100644 (file)
index 0000000..02c0060
--- /dev/null
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.Constant;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+abstract class AbstractGeneratedTypeBuilder implements GeneratedTypeBuilder {
+
+    private final String packageName;
+    private String comment = "";
+    private final String name;
+
+    private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<>();
+    private final List<Type> implementsTypes = new ArrayList<>();
+    private final List<EnumBuilder> enumDefinitions = new ArrayList<>();
+    private final List<Constant> constants = new ArrayList<>();
+    private final List<MethodSignatureBuilder> methodDefinitions = new ArrayList<>();
+    private final List<GeneratedTypeBuilder> enclosedTypes = new ArrayList<>();
+    private final List<GeneratedTOBuilder> enclosingTransferObjects = new ArrayList<>();
+    private boolean isAbstract;
+
+    public AbstractGeneratedTypeBuilder(final String packageName, final String name) {
+        if (packageName == null) {
+            throw new IllegalArgumentException("Package Name for Generated Type cannot be null!");
+        }
+        if (name == null) {
+            throw new IllegalArgumentException("Name of Generated Type cannot be null!");
+        }
+        this.packageName = packageName;
+        this.name = name;
+    }
+
+    @Override
+    public String getPackageName() {
+        return packageName;
+    }
+
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    @Override
+    public String getFullyQualifiedName() {
+        return packageName + "." + name;
+    }
+
+
+    protected String getComment() {
+        return comment;
+    }
+
+    protected List<AnnotationTypeBuilder> getAnnotations() {
+        return annotationBuilders;
+    }
+
+    protected boolean isAbstract() {
+        return isAbstract;
+    }
+
+    protected List<Type> getImplementsTypes() {
+        return implementsTypes;
+    }
+
+    protected List<EnumBuilder> getEnumerations() {
+        return enumDefinitions;
+    }
+
+    protected List<Constant> getConstants() {
+        return constants;
+    }
+
+    protected List<MethodSignatureBuilder> getMethodDefinitions() {
+        return methodDefinitions;
+    }
+
+    protected List<GeneratedTypeBuilder> getEnclosedTypes() {
+        return enclosedTypes;
+    }
+
+    protected List<GeneratedTOBuilder> getEnclosedTransferObjects() {
+        return enclosingTransferObjects;
+    }
+
+    @Override
+    public GeneratedTypeBuilder addEnclosingType(String name) {
+        if (name == null) {
+            throw new IllegalArgumentException("Name for Enclosing Generated Type cannot be null!");
+        }
+        GeneratedTypeBuilder builder = new GeneratedTOBuilderImpl(getFullyQualifiedName(), name);
+        enclosedTypes.add(builder);
+        return builder;
+    }
+
+    @Override
+    public GeneratedTOBuilder addEnclosingTransferObject(String name) {
+        if (name == null) {
+            throw new IllegalArgumentException("Name for Enclosing Generated Transfer Object cannot be null!");
+        }
+        GeneratedTOBuilder builder = new GeneratedTOBuilderImpl(getFullyQualifiedName(), name);
+        enclosingTransferObjects.add(builder);
+        return builder;
+    }
+
+    @Override
+    public void addComment(String comment) {
+        this.comment = comment;
+    }
+
+    @Override
+    public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
+        if (packageName == null) {
+            throw new IllegalArgumentException("Package Name for Annotation Type cannot be null!");
+        }
+        if (name == null) {
+            throw new IllegalArgumentException("Name of Annotation Type cannot be null!");
+        }
+
+        final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(packageName, name);
+        annotationBuilders.add(builder);
+        return builder;
+    }
+
+     @Override
+     public void setAbstract(boolean isAbstract) {
+         this.isAbstract = isAbstract;
+     }
+
+     @Override
+    public boolean addImplementsType(Type genType) {
+        if (genType == null) {
+            throw new IllegalArgumentException("Type cannot be null");
+        }
+        return implementsTypes.add(genType);
+    }
+
+    @Override
+    public Constant addConstant(Type type, String name, Object value) {
+        if (type == null) {
+            throw new IllegalArgumentException("Returning Type for Constant cannot be null!");
+        }
+        if (name == null) {
+            throw new IllegalArgumentException("Name of constant cannot be null!");
+        }
+
+        final Constant constant = new ConstantImpl(this, type, name, value);
+        constants.add(constant);
+        return constant;
+    }
+
+    @Override
+    public EnumBuilder addEnumeration(String name) {
+        if (name == null) {
+            throw new IllegalArgumentException("Name of enumeration cannot be null!");
+        }
+        final EnumBuilder builder = new EnumerationBuilderImpl(
+                getFullyQualifiedName(), name);
+        enumDefinitions.add(builder);
+        return builder;
+    }
+
+    @Override
+    public MethodSignatureBuilder addMethod(String name) {
+        if (name == null) {
+            throw new IllegalArgumentException("Name of method cannot be null!");
+        }
+        final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(name);
+        builder.setAccessModifier(AccessModifier.PUBLIC);
+        builder.setAbstract(true);
+        methodDefinitions.add(builder);
+        return builder;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+        result = prime * result
+                + ((getPackageName() == null) ? 0 : getPackageName().hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        AbstractGeneratedTypeBuilder other = (AbstractGeneratedTypeBuilder) obj;
+        if (getName() == null) {
+            if (other.getName() != null) {
+                return false;
+            }
+        } else if (!getName().equals(other.getName())) {
+            return false;
+        }
+        if (getPackageName() == null) {
+            if (other.getPackageName() != null) {
+                return false;
+            }
+        } else if (!getPackageName().equals(other.getPackageName())) {
+            return false;
+        }
+        return true;
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractTypeMember.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractTypeMember.java
new file mode 100644 (file)
index 0000000..5719d35
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.TypeMember;
+
+import java.util.Collections;
+import java.util.List;
+
+abstract class AbstractTypeMember implements TypeMember {
+
+    private final String name;
+    private final String comment;
+    private final Type definingType;
+    private final Type returnType;
+    private final List<AnnotationType> annotations;
+    private final boolean isFinal;
+    private final AccessModifier accessModifier;
+
+    public AbstractTypeMember(final Type definingType, final String name,  final List<AnnotationType> annotations,
+                              final String comment, final AccessModifier accessModifier, final Type returnType,
+                              boolean isFinal) {
+        super();
+        this.definingType = definingType;
+        this.name = name;
+        this.annotations = Collections.unmodifiableList(annotations);
+        this.comment = comment;
+        this.accessModifier = accessModifier;
+        this.returnType = returnType;
+        this.isFinal = isFinal;
+    }
+
+    @Override
+    public List<AnnotationType> getAnnotations() {
+        return annotations;
+    }
+
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    @Override
+    public String getComment() {
+        return comment;
+    }
+
+    @Override
+    public Type getDefiningType() {
+        return definingType;
+    }
+
+    @Override
+    public AccessModifier getAccessModifier() {
+        return accessModifier;
+    }
+
+    @Override
+    public Type getReturnType() {
+        return returnType;
+    }
+
+    @Override
+    public boolean isFinal() {
+        return isFinal;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+        result = prime * result
+                + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        MethodSignatureImpl other = (MethodSignatureImpl) obj;
+        if (getName() == null) {
+            if (other.getName() != null) {
+                return false;
+            }
+        } else if (!getName().equals(other.getName())) {
+            return false;
+        }
+        if (getReturnType() == null) {
+            if (other.getReturnType() != null) {
+                return false;
+            }
+        } else if (!getReturnType().equals(other.getReturnType())) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("MethodSignatureImpl [name=");
+        builder.append(getName());
+        builder.append(", comment=");
+        builder.append(getComment());
+        if (getDefiningType() != null) {
+            builder.append(", definingType=");
+            builder.append(getDefiningType().getPackageName());
+            builder.append(".");
+            builder.append(getDefiningType().getName());
+        } else {
+            builder.append(", definingType= null");
+        }
+        builder.append(", returnType=");
+        builder.append(getReturnType());
+        builder.append(", annotations=");
+        builder.append(getAnnotations());
+        builder.append("]");
+        return builder.toString();
+    }
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java
new file mode 100644 (file)
index 0000000..391c3af
--- /dev/null
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.TypeMemberBuilder;
+
+import java.util.ArrayList;
+import java.util.List;
+
+abstract class AbstractTypeMemberBuilder implements TypeMemberBuilder {
+    private final String name;
+    private Type returnType;
+    private final List<AnnotationTypeBuilder> annotationBuilders;
+    private String comment = "";
+    private boolean isFinal;
+    private AccessModifier accessModifier;
+
+    public AbstractTypeMemberBuilder(final String name) {
+        this.name = name;
+        this.annotationBuilders = new ArrayList<>();
+    }
+
+    @Override
+    public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
+        if (packageName == null) {
+            throw new IllegalArgumentException("Annotation Type cannot have package name null!");
+        }
+        if (name == null) {
+            throw new IllegalArgumentException("Annotation Type cannot have name as null!");
+        }
+        final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
+                    packageName, name);
+        annotationBuilders.add(builder);
+        return builder;
+    }
+
+    protected Type getReturnType() {
+        return returnType;
+    }
+
+    protected List<AnnotationTypeBuilder> getAnnotationBuilders() {
+        return annotationBuilders;
+    }
+
+    protected String getComment() {
+        return comment;
+    }
+
+    protected boolean isFinal() {
+        return isFinal;
+    }
+
+    protected AccessModifier getAccessModifier() {
+        return accessModifier;
+    }
+
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    @Override
+    public void setReturnType(Type returnType) {
+        if (returnType == null) {
+            throw new IllegalArgumentException("Return Type of member cannot be null!");
+        }
+        this.returnType = returnType;
+    }
+
+    @Override
+    public void setAccessModifier(AccessModifier modifier) {
+        if (modifier == null) {
+            throw new IllegalArgumentException("Access Modifier for member type cannot be null!");
+        }
+        this.accessModifier = modifier;
+    }
+
+    @Override
+    public void setComment(String comment) {
+        if (comment == null) {
+            throw new IllegalArgumentException("Comment string cannot be null!");
+        }
+        this.comment = comment;
+    }
+
+    @Override
+    public void setFinal(boolean isFinal) {
+        this.isFinal = isFinal;
+    }
+
+    protected List<AnnotationType> toAnnotationTypes() {
+        final List<AnnotationType> annotations = new ArrayList<>();
+        for (final AnnotationTypeBuilder annotBuilder : getAnnotationBuilders()) {
+            if (annotBuilder != null) {
+                annotations.add(annotBuilder.toInstance());
+            }
+        }
+        return annotations;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+        result = prime * result
+                + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        MethodSignatureBuilderImpl other = (MethodSignatureBuilderImpl) obj;
+        if (getName() == null) {
+            if (other.getName() != null) {
+                return false;
+            }
+        } else if (!getName().equals(other.getName())) {
+            return false;
+        }
+        if (getReturnType() == null) {
+            if (other.getReturnType() != null) {
+                return false;
+            }
+        } else if (!getReturnType().equals(other.getReturnType())) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("GeneratedPropertyImpl [name=");
+        builder.append(getName());
+        builder.append(", annotations=");
+        builder.append(getAnnotationBuilders());
+        builder.append(", comment=");
+        builder.append(getComment());
+        builder.append(", returnType=");
+        builder.append(getReturnType());
+        builder.append(", isFinal=");
+        builder.append(isFinal());
+        builder.append(", modifier=");
+        builder.append(getAccessModifier());
+        builder.append("]");
+        return builder.toString();
+    }
+}
index 6eaa7695638a9b7d0d76fe1fed89cd997082cdd5..c125af556a14551eb9af51c3faa70b87460f55e5 100644 (file)
@@ -1,3 +1,10 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.binding.generator.util.generated.type.builder;
 
 import java.util.ArrayList;
@@ -18,9 +25,8 @@ final class AnnotationTypeBuilderImpl implements AnnotationTypeBuilder {
         super();
         this.packageName = packageName;
         this.name = name;
-        
-        annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
-        parameters = new ArrayList<AnnotationType.Parameter>();
+        annotationBuilders = new ArrayList<>();
+        parameters = new ArrayList<>();
     }
 
     @Override
@@ -33,6 +39,11 @@ final class AnnotationTypeBuilderImpl implements AnnotationTypeBuilder {
         return name;
     }
 
+    @Override
+    public String getFullyQualifiedName() {
+        return packageName + "." + name;
+    }
+
     @Override
     public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
         if (packageName != null && name != null) {
@@ -134,7 +145,7 @@ final class AnnotationTypeBuilderImpl implements AnnotationTypeBuilder {
             this.packageName = packageName;
             this.name = name;
             
-            this.annotations = new ArrayList<AnnotationType>();
+            this.annotations = new ArrayList<>();
             for (final AnnotationTypeBuilder builder : annotationBuilders) {
                 annotations.add(builder.toInstance());
             }
@@ -142,7 +153,7 @@ final class AnnotationTypeBuilderImpl implements AnnotationTypeBuilder {
             this.annotations = Collections.unmodifiableList(annotations); 
             this.parameters = Collections.unmodifiableList(parameters);
             
-            paramNames = new ArrayList<String>();
+            paramNames = new ArrayList<>();
             for (final AnnotationType.Parameter parameter : parameters) {
                 paramNames.add(parameter.getName());
             }
@@ -159,6 +170,11 @@ final class AnnotationTypeBuilderImpl implements AnnotationTypeBuilder {
             return name;
         }
 
+        @Override
+        public String getFullyQualifiedName() {
+            return packageName + "." + name;
+        }
+
         @Override
         public List<AnnotationType> getAnnotations() {
             return annotations;
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/ConstantBuilderImpl.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/ConstantBuilderImpl.java
deleted file mode 100644 (file)
index 16e89e0..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.binding.generator.util.generated.type.builder;
-
-import org.opendaylight.controller.sal.binding.model.api.Constant;
-import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.ConstantBuilder;
-
-final class ConstantBuilderImpl implements ConstantBuilder {
-
-    private final Type type;
-    private final String name;
-    private Object value;
-
-    public ConstantBuilderImpl(Type type, String name, Object value) {
-        super();
-        this.type = type;
-        this.name = name;
-        this.value = value;
-    }
-
-    public ConstantBuilderImpl(Type type, String name) {
-        super();
-        this.type = type;
-        this.name = name;
-    }
-
-    @Override
-    public void assignValue(Object value) {
-        this.value = value;
-    }
-
-    @Override
-    public Constant toInstance(final Type definingType) {
-        return new ConstantImpl(definingType, type, name, value);
-    }
-
-    private static final class ConstantImpl implements Constant {
-
-        final Type definingType;
-        private final Type type;
-        private final String name;
-        private final Object value;
-
-        public ConstantImpl(final Type definingType, final Type type,
-                final String name, final Object value) {
-            super();
-            this.definingType = definingType;
-            this.type = type;
-            this.name = name;
-            this.value = value;
-        }
-
-        @Override
-        public Type getDefiningType() {
-            return definingType;
-        }
-
-        @Override
-        public Type getType() {
-            return type;
-        }
-
-        @Override
-        public String getName() {
-            return name;
-        }
-
-        @Override
-        public Object getValue() {
-            return value;
-        }
-        
-        @Override
-        public String toFormattedString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append(type);
-            builder.append(" ");
-            builder.append(name);
-            builder.append(" ");
-            builder.append(value);
-            return builder.toString();
-        }
-
-        /*
-         * (non-Javadoc)
-         * 
-         * @see java.lang.Object#hashCode()
-         */
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((name == null) ? 0 : name.hashCode());
-            result = prime * result + ((type == null) ? 0 : type.hashCode());
-            return result;
-        }
-
-        /*
-         * (non-Javadoc)
-         * 
-         * @see java.lang.Object#equals(java.lang.Object)
-         */
-        @Override
-        public boolean equals(Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            ConstantImpl other = (ConstantImpl) obj;
-            if (name == null) {
-                if (other.name != null) {
-                    return false;
-                }
-            } else if (!name.equals(other.name)) {
-                return false;
-            }
-            if (type == null) {
-                if (other.type != null) {
-                    return false;
-                }
-            } else if (!type.equals(other.type)) {
-                return false;
-            }
-            if (value == null) {
-                if (other.value != null) {
-                    return false;
-                }
-            } else if (!value.equals(other.value)) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("Constant [type=");
-            builder.append(type);
-            builder.append(", name=");
-            builder.append(name);
-            builder.append(", value=");
-            builder.append(value);
-            if (definingType != null) {
-                builder.append(", definingType=");
-                builder.append(definingType.getPackageName());
-                builder.append(".");
-                builder.append(definingType.getName());
-            } else {
-                builder.append(", definingType= null");
-            }
-            builder.append("]");
-            return builder.toString();
-        }
-    }
-}
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/ConstantImpl.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/ConstantImpl.java
new file mode 100644 (file)
index 0000000..5d7ba4e
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.Constant;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+final class ConstantImpl implements Constant {
+
+    final Type definingType;
+    private final Type type;
+    private final String name;
+    private final Object value;
+
+    public ConstantImpl(final Type definingType, final Type type,
+                        final String name, final Object value) {
+        super();
+        this.definingType = definingType;
+        this.type = type;
+        this.name = name;
+        this.value = value;
+    }
+
+    @Override
+    public Type getDefiningType() {
+        return definingType;
+    }
+
+    @Override
+    public Type getType() {
+        return type;
+    }
+
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    @Override
+    public Object getValue() {
+        return value;
+    }
+
+    @Override
+    public String toFormattedString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append(type);
+        builder.append(" ");
+        builder.append(name);
+        builder.append(" ");
+        builder.append(value);
+        return builder.toString();
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((name == null) ? 0 : name.hashCode());
+        result = prime * result + ((type == null) ? 0 : type.hashCode());
+        return result;
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        ConstantImpl other = (ConstantImpl) obj;
+        if (name == null) {
+            if (other.name != null) {
+                return false;
+            }
+        } else if (!name.equals(other.name)) {
+            return false;
+        }
+        if (type == null) {
+            if (other.type != null) {
+                return false;
+            }
+        } else if (!type.equals(other.type)) {
+            return false;
+        }
+        if (value == null) {
+            if (other.value != null) {
+                return false;
+            }
+        } else if (!value.equals(other.value)) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("Constant [type=");
+        builder.append(type);
+        builder.append(", name=");
+        builder.append(name);
+        builder.append(", value=");
+        builder.append(value);
+        if (definingType != null) {
+            builder.append(", definingType=");
+            builder.append(definingType.getPackageName());
+            builder.append(".");
+            builder.append(definingType.getName());
+        } else {
+            builder.append(", definingType= null");
+        }
+        builder.append("]");
+        return builder.toString();
+    }
+}
index 62945ea4517253c6d5643cfd9e759887c493ed5c..8bf5b5d4cb587d13270773a4104e5a82965edca9 100644 (file)
@@ -27,7 +27,7 @@ public final class EnumerationBuilderImpl implements EnumBuilder {
         super();
         this.packageName = packageName;
         this.name = name;
-        values = new ArrayList<Enumeration.Pair>();
+        values = new ArrayList<>();
     }
     
     @Override
@@ -39,7 +39,12 @@ public final class EnumerationBuilderImpl implements EnumBuilder {
     public String getName() {
         return name;
     }
-    
+
+    @Override
+    public String getFullyQualifiedName() {
+        return packageName + "." + name;
+    }
+
     @Override
     public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
         if (packageName != null && name != null) {
@@ -220,7 +225,7 @@ public final class EnumerationBuilderImpl implements EnumBuilder {
         private final String packageName;
         private final String name;
         private final List<Pair> values;
-        private List<AnnotationType> annotations = new ArrayList<AnnotationType>();
+        private List<AnnotationType> annotations = new ArrayList<>();
         
         public EnumerationImpl(final Type definingType,
                 final List<AnnotationTypeBuilder> annotationBuilders,
@@ -252,6 +257,11 @@ public final class EnumerationBuilderImpl implements EnumBuilder {
             return name;
         }
 
+        @Override
+        public String getFullyQualifiedName() {
+            return packageName + "." + name;
+        }
+
         @Override
         public List<Pair> getValues() {
             return values;
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java
new file mode 100644 (file)
index 0000000..9b61163
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
+
+import java.util.List;
+
+final class GeneratedPropertyBuilderImpl extends AbstractTypeMemberBuilder implements GeneratedPropertyBuilder {
+
+    private boolean isReadOnly;
+
+    public GeneratedPropertyBuilderImpl(String name) {
+        super(name);
+    }
+
+    @Override
+    public void setReadOnly(boolean isReadOnly) {
+        this.isReadOnly = isReadOnly;
+    }
+
+    @Override
+    public GeneratedProperty toInstance(Type definingType) {
+        final List<AnnotationType> annotations = toAnnotationTypes();
+        return new GeneratedPropertyImpl(definingType, getName(), annotations, getComment(), getAccessModifier(),
+                getReturnType(), isFinal(), isReadOnly);
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("GeneratedPropertyImpl [name=");
+        builder.append(getName());
+        builder.append(", annotations=");
+        builder.append(getAnnotationBuilders());
+        builder.append(", comment=");
+        builder.append(getComment());
+        builder.append(", returnType=");
+        builder.append(getReturnType());
+        builder.append(", isFinal=");
+        builder.append(isFinal());
+        builder.append(", isReadOnly=");
+        builder.append(isReadOnly);
+        builder.append(", modifier=");
+        builder.append(getAccessModifier());
+        builder.append("]");
+        return builder.toString();
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedPropertyImpl.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/GeneratedPropertyImpl.java
new file mode 100644 (file)
index 0000000..6d11bfd
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+import java.util.List;
+
+final class GeneratedPropertyImpl extends AbstractTypeMember implements GeneratedProperty {
+
+    private boolean isReadOnly;
+
+    public GeneratedPropertyImpl(Type definingType, String name, List<AnnotationType> annotations, String comment,
+                                 AccessModifier accessModifier, Type returnType, boolean isFinal, boolean isReadOnly) {
+        super(definingType, name, annotations, comment, accessModifier, returnType, isFinal);
+        this.isReadOnly = isReadOnly;
+    }
+
+    @Override
+    public boolean isReadOnly() {
+        return isReadOnly;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("GeneratedPropertyImpl [name=");
+        builder.append(getName());
+        builder.append(", annotations=");
+        builder.append(getAnnotations());
+        builder.append(", comment=");
+        builder.append(getComment());
+        if (getDefiningType() != null) {
+            builder.append(", parent=");
+            builder.append(getDefiningType().getPackageName());
+            builder.append(".");
+            builder.append(getDefiningType().getName());
+        } else {
+            builder.append(", parent=null");
+        }
+        builder.append(", returnType=");
+        builder.append(getReturnType());
+        builder.append(", isFinal=");
+        builder.append(isFinal());
+        builder.append(", isReadOnly=");
+        builder.append(isReadOnly);
+        builder.append(", modifier=");
+        builder.append(getAccessModifier());
+        builder.append("]");
+        return builder.toString();
+    }
+}
index f1683fdc6435e86ccb98ea36389c1a24053b9d13..de3e19223f5fca053240f27ab1d0ca3031d63be0 100644 (file)
  */
 package org.opendaylight.controller.binding.generator.util.generated.type.builder;
 
+import org.opendaylight.controller.sal.binding.model.api.*;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
-import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
-import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
-import org.opendaylight.controller.sal.binding.model.api.Constant;
-import org.opendaylight.controller.sal.binding.model.api.Enumeration;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferIdentityObject;
-import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
-import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
-import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.ConstantBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
-
-public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
-    private String packageName;
-    private final String name;
-    private String comment = "";
+public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder implements GeneratedTOBuilder {
 
     private GeneratedTransferObject extendsType;
-    private final List<Type> implementsTypes = new ArrayList<Type>();
-    private final List<EnumBuilder> enumerations = new ArrayList<EnumBuilder>();
-    private final List<GeneratedPropertyBuilder> properties = new ArrayList<GeneratedPropertyBuilder>();
-    private final List<GeneratedPropertyBuilder> equalsProperties = new ArrayList<GeneratedPropertyBuilder>();
-    private final List<GeneratedPropertyBuilder> hashProperties = new ArrayList<GeneratedPropertyBuilder>();
-    private final List<GeneratedPropertyBuilder> toStringProperties = new ArrayList<GeneratedPropertyBuilder>();
-
-    private final List<ConstantBuilder> constantDefintions = new ArrayList<ConstantBuilder>();
-    private final List<MethodSignatureBuilder> methodDefinitions = new ArrayList<MethodSignatureBuilder>();
-    private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
+    private final List<GeneratedPropertyBuilder> properties = new ArrayList<>();
+    private final List<GeneratedPropertyBuilder> equalsProperties = new ArrayList<>();
+    private final List<GeneratedPropertyBuilder> hashProperties = new ArrayList<>();
+    private final List<GeneratedPropertyBuilder> toStringProperties = new ArrayList<>();
 
     public GeneratedTOBuilderImpl(String packageName, String name) {
-        super();
-        this.packageName = packageName;
-        this.name = name;
-    }
-
-    @Override
-    public String getPackageName() {
-        return packageName;
-    }
-
-    @Override
-    public String getName() {
-        return name;
-    }
-
-    @Override
-    public Type getParentType() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public void addComment(final String comment) {
-        this.comment = comment;
-    }
-
-    @Override
-    public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
-        if (packageName != null && name != null) {
-            final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
-                    packageName, name);
-            if (annotationBuilders.add(builder)) {
-                return builder;
-            }
-        }
-        return null;
-    }
-
-    @Override
-    public boolean addImplementsType(final Type genType) {
-        if (genType != null) {
-            return implementsTypes.add(genType);
-        }
-        return false;
+        super(packageName, name);
+        setAbstract(false);
     }
 
     @Override
-    public boolean addExtendsType(final GeneratedTransferObject genTransObj) {
-        if (genTransObj != null) {
-            extendsType = genTransObj;
-            return true;
+    public void setExtendsType(final GeneratedTransferObject genTransObj) {
+        if (genTransObj == null) {
+            throw new IllegalArgumentException("Generated Transfer Object cannot be null!");
         }
-        return false;
-    }
-
-    @Override
-    public EnumBuilder addEnumeration(String name) {
-        final String innerPackageName = packageName + "." + this.name;
-        final EnumBuilder builder = new EnumerationBuilderImpl(innerPackageName,
-                name);
-        enumerations.add(builder);
-        return builder;
+        extendsType = genTransObj;
     }
 
     @Override
-    public ConstantBuilder addConstant(Type type, String name, Object value) {
-        final ConstantBuilder builder = new ConstantBuilderImpl(type, name,
-                value);
-        constantDefintions.add(builder);
+    public GeneratedPropertyBuilder addProperty(String name) {
+        final GeneratedPropertyBuilder builder = new GeneratedPropertyBuilderImpl(name);
+        builder.setAccessModifier(AccessModifier.PUBLIC);
+        properties.add(builder);
         return builder;
     }
 
+    /**
+     * Add new Method Signature definition for Generated Type Builder and
+     * returns Method Signature Builder for specifying all Method parameters.
+     * <br>
+     * Name of Method cannot be <code>null</code>,
+     * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+     * <br>
+     * By <i>Default</i> the MethodSignatureBuilder SHOULD be pre-set as
+     * {@link MethodSignatureBuilder#setAbstract(false)}, {@link MethodSignatureBuilder#setFinal(false)} and
+     * {@link MethodSignatureBuilder#setAccessModifier(PUBLIC)}
+     *
+     * @param name Name of Method
+     * @return <code>new</code> instance of Method Signature Builder.
+     */
     @Override
     public MethodSignatureBuilder addMethod(String name) {
-        final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(
-                this, name);
-        methodDefinitions.add(builder);
-        return builder;
-    }
-
-    @Override
-    public GeneratedPropertyBuilder addProperty(String name) {
-        final GeneratedPropertyBuilder builder = new GeneratedPropertyBuilderImpl(
-                name);
-        properties.add(builder);
+        final MethodSignatureBuilder builder = super.addMethod(name);
+        builder.setAbstract(false);
         return builder;
     }
 
@@ -150,381 +81,83 @@ public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
 
     @Override
     public GeneratedTransferObject toInstance() {
-        return new GeneratedTransferObjectImpl(packageName, name, comment,
-                annotationBuilders, extendsType, implementsTypes,
-                constantDefintions, enumerations, methodDefinitions,
-                properties, equalsProperties, hashProperties,
-                toStringProperties);
-    }
-
-    @Override
-    public GeneratedTransferObject toIdentityInstance() {
-        return new GeneratedTransferIdentityObjectImpl(packageName, name, comment,
-                annotationBuilders, extendsType, implementsTypes,
-                constantDefintions, enumerations, methodDefinitions,
-                properties, equalsProperties, hashProperties,
-                toStringProperties);
-    }
-
-    private static final class GeneratedPropertyBuilderImpl implements
-            GeneratedPropertyBuilder {
-
-        private final String name;
-        private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
-        private Type returnType;
-        private final List<MethodSignature.Parameter> parameters;
-        private String comment = "";
-        private AccessModifier accessModifier;
-        private boolean isFinal;
-        private boolean isReadOnly;
-
-        public GeneratedPropertyBuilderImpl(final String name) {
-            super();
-            this.name = name;
-            parameters = new ArrayList<MethodSignature.Parameter>();
-            isFinal = true;
-            this.isReadOnly = true;
-            accessModifier = AccessModifier.PUBLIC;
-        }
-
-        public String getName() {
-            return name;
-        }
-
-        @Override
-        public AnnotationTypeBuilder addAnnotation(String packageName,
-                String name) {
-            if (packageName != null && name != null) {
-                final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
-                        packageName, name);
-                if (annotationBuilders.add(builder)) {
-                    return builder;
-                }
-            }
-            return null;
-        }
-
-        @Override
-        public boolean addReturnType(Type returnType) {
-            if (returnType != null) {
-                this.returnType = returnType;
-                this.parameters.add(new MethodParameterImpl(name, returnType));
-                return true;
-            }
-            return false;
-        }
-
-        @Override
-        public void accessorModifier(final AccessModifier modifier) {
-            accessModifier = modifier;
-        }
-
-        @Override
-        public void addComment(String comment) {
-            if (comment != null) {
-                this.comment = comment;
-            }
-        }
-
-        @Override
-        public void setFinal(boolean isFinal) {
-            this.isFinal = isFinal;
-        }
-
-        @Override
-        public void setReadOnly(boolean isReadOnly) {
-            this.isReadOnly = isReadOnly;
-        }
-
-        @Override
-        public GeneratedProperty toInstance(final Type definingType) {
-            return new GeneratedPropertyImpl(name, comment, annotationBuilders,
-                    definingType, returnType, isFinal, isReadOnly, parameters,
-                    accessModifier);
-        }
-    }
-
-    private static final class GeneratedPropertyImpl implements
-            GeneratedProperty {
-
-        private final String name;
-        private List<AnnotationType> annotations;
-        private final String comment;
-        private final Type parent;
-        private final Type returnType;
-        private final boolean isFinal;
-        private final boolean isReadOnly;
-        private final List<MethodSignature.Parameter> parameters;
-        private final AccessModifier modifier;
-
-        public GeneratedPropertyImpl(final String name, final String comment,
-                final List<AnnotationTypeBuilder> annotationBuilders,
-                final Type parent, final Type returnType,
-                final boolean isFinal, final boolean isReadOnly,
-                final List<Parameter> parameters, final AccessModifier modifier) {
-            super();
-            this.name = name;
-            this.annotations = new ArrayList<AnnotationType>();
-            for (final AnnotationTypeBuilder builder : annotationBuilders) {
-                this.annotations.add(builder.toInstance());
-            }
-            this.annotations = Collections.unmodifiableList(this.annotations);
-            this.comment = comment;
-            this.parent = parent;
-            this.returnType = returnType;
-            this.isFinal = isFinal;
-            this.isReadOnly = isReadOnly;
-            this.parameters = Collections.unmodifiableList(parameters);
-            this.modifier = modifier;
-        }
-
-        @Override
-        public String getName() {
-            return name;
-        }
-
-        @Override
-        public String getComment() {
-            return comment;
-        }
-
-        @Override
-        public Type getDefiningType() {
-            return parent;
-        }
-
-        @Override
-        public List<AnnotationType> getAnnotations() {
-            return annotations;
-        }
-
-        @Override
-        public Type getReturnType() {
-            return returnType;
-        }
-
-        @Override
-        public List<Parameter> getParameters() {
-            return parameters;
-        }
-
-        @Override
-        public AccessModifier getAccessModifier() {
-            return modifier;
-        }
-
-        @Override
-        public boolean isReadOnly() {
-            return isReadOnly;
-        }
-
-        @Override
-        public boolean isFinal() {
-            return isFinal;
-        }
-
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((name == null) ? 0 : name.hashCode());
-            result = prime * result
-                    + ((parameters == null) ? 0 : parameters.hashCode());
-            result = prime * result
-                    + ((returnType == null) ? 0 : returnType.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            GeneratedPropertyImpl other = (GeneratedPropertyImpl) obj;
-            if (name == null) {
-                if (other.name != null) {
-                    return false;
-                }
-            } else if (!name.equals(other.name)) {
-                return false;
-            }
-            if (parameters == null) {
-                if (other.parameters != null) {
-                    return false;
-                }
-            } else if (!parameters.equals(other.parameters)) {
-                return false;
-            }
-            if (returnType == null) {
-                if (other.returnType != null) {
-                    return false;
-                }
-            } else if (!returnType.getPackageName().equals(
-                    other.returnType.getPackageName())) {
-                return false;
-            } else if (!returnType.getName().equals(other.returnType.getName())) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("GeneratedPropertyImpl [name=");
-            builder.append(name);
-            builder.append(", annotations=");
-            builder.append(annotations);
-            builder.append(", comment=");
-            builder.append(comment);
-            if (parent != null) {
-                builder.append(", parent=");
-                builder.append(parent.getPackageName());
-                builder.append(".");
-                builder.append(parent.getName());
-            } else {
-                builder.append(", parent=null");
-            }
-            builder.append(", returnType=");
-            builder.append(returnType);
-            builder.append(", isFinal=");
-            builder.append(isFinal);
-            builder.append(", isReadOnly=");
-            builder.append(isReadOnly);
-            builder.append(", parameters=");
-            builder.append(parameters);
-            builder.append(", modifier=");
-            builder.append(modifier);
-            builder.append("]");
-            return builder.toString();
-        }
-    }
-
-    private static class GeneratedTransferObjectImpl implements
+        return new GeneratedTransferObjectImpl(null, getPackageName(), getName(), getComment(),
+                getAnnotations(), isAbstract(), extendsType, getImplementsTypes(), getEnclosedTypes(),
+                getEnclosedTransferObjects(), getConstants(), getEnumerations(), getMethodDefinitions(), properties,
+                equalsProperties, hashProperties, toStringProperties);
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("GeneratedTransferObject [packageName=");
+        builder.append(getPackageName());
+        builder.append(", name=");
+        builder.append(getName());
+        builder.append(", comment=");
+        builder.append(getComment());
+        builder.append(", constants=");
+        builder.append(getConstants());
+        builder.append(", enumerations=");
+        builder.append(getEnumerations());
+        builder.append(", properties=");
+        builder.append(properties);
+        builder.append(", equalsProperties=");
+        builder.append(equalsProperties);
+        builder.append(", hashCodeProperties=");
+        builder.append(hashProperties);
+        builder.append(", stringProperties=");
+        builder.append(toStringProperties);
+        builder.append(", annotations=");
+        builder.append(getAnnotations());
+        builder.append(", methods=");
+        builder.append(getMethodDefinitions());
+        builder.append("]");
+        return builder.toString();
+    }
+
+    private static final class GeneratedTransferObjectImpl extends AbstractGeneratedType implements
             GeneratedTransferObject {
 
-        private final String packageName;
-        private final String name;
-        private final String comment;
-        private final List<Constant> constants;
-        private final List<Enumeration> enumerations;
         private final List<GeneratedProperty> properties;
         private final List<GeneratedProperty> equalsProperties;
         private final List<GeneratedProperty> hashCodeProperties;
         private final List<GeneratedProperty> stringProperties;
-        private final List<AnnotationType> annotations;
-        private final List<MethodSignature> methods;
         private final GeneratedTransferObject extendsType;
-        private final List<Type> implementsTypes;
 
-        public GeneratedTransferObjectImpl(final String packageName,
-                final String name, final String comment,
-                final List<AnnotationTypeBuilder> annotationBuilders,
-                final GeneratedTransferObject extendsType,
-                final List<Type> implementsTypes,
-                final List<ConstantBuilder> constantBuilders,
-                final List<EnumBuilder> enumBuilders,
-                final List<MethodSignatureBuilder> methodBuilders,
-                final List<GeneratedPropertyBuilder> propBuilers,
-                final List<GeneratedPropertyBuilder> equalsBuilers,
-                final List<GeneratedPropertyBuilder> hashCodeBuilers,
-                final List<GeneratedPropertyBuilder> stringBuilers) {
-            super();
-            this.packageName = packageName;
-            this.name = name;
-            this.comment = comment;
-            this.annotations = toUnmodifiableAnnotations(annotationBuilders);
+        GeneratedTransferObjectImpl(final Type parent,
+                    final String packageName,
+                                           final String name, final String comment,
+                                           final List<AnnotationTypeBuilder> annotationBuilders,
+                                           final boolean isAbstract,
+                                           final GeneratedTransferObject extendsType,
+                                           final List<Type> implementsTypes,
+                                           final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+                                           final List<GeneratedTOBuilder> enclosedGenTOBuilders,
+                                           final List<Constant> constants,
+                                           final List<EnumBuilder> enumBuilders,
+                                           final List<MethodSignatureBuilder> methodBuilders,
+                                           final List<GeneratedPropertyBuilder> propBuilders,
+                                           final List<GeneratedPropertyBuilder> equalsBuilders,
+                                           final List<GeneratedPropertyBuilder> hashCodeBuilders,
+                                           final List<GeneratedPropertyBuilder> stringBuilders) {
+            super(parent, packageName, name, comment, annotationBuilders, isAbstract, implementsTypes,
+                    enclosedGenTypeBuilders,
+                    enclosedGenTOBuilders, enumBuilders, constants, methodBuilders);
             this.extendsType = extendsType;
-            this.implementsTypes = Collections
-                    .unmodifiableList(implementsTypes);
-            this.constants = toUnmodifiableConstant(constantBuilders);
-            this.enumerations = toUnmodifiableEnumerations(enumBuilders);
-            this.properties = toUnmodifiableProperties(propBuilers);
-            this.methods = toUnmodifiableMethods(methodBuilders);
-            this.equalsProperties = toUnmodifiableProperties(equalsBuilers);
-            this.hashCodeProperties = toUnmodifiableProperties(hashCodeBuilers);
-            this.stringProperties = toUnmodifiableProperties(stringBuilers);
-        }
-
-        private List<AnnotationType> toUnmodifiableAnnotations(
-                final List<AnnotationTypeBuilder> annotationBuilders) {
-            final List<AnnotationType> annotations = new ArrayList<AnnotationType>();
-            for (final AnnotationTypeBuilder builder : annotationBuilders) {
-                annotations.add(builder.toInstance());
-            }
-            return Collections.unmodifiableList(annotations);
-        }
-
-        private List<Enumeration> toUnmodifiableEnumerations(
-                final List<EnumBuilder> enumBuilders) {
-            final List<Enumeration> enumerations = new ArrayList<Enumeration>();
-            for (final EnumBuilder builder : enumBuilders) {
-                enumerations.add(builder.toInstance(this));
-            }
-            return Collections.unmodifiableList(enumerations);
-        }
-
-        private List<Constant> toUnmodifiableConstant(
-                final List<ConstantBuilder> constBuilders) {
-            final List<Constant> constants = new ArrayList<Constant>();
-            for (final ConstantBuilder builder : constBuilders) {
-                constants.add(builder.toInstance(this));
-            }
-            return Collections.unmodifiableList(constants);
-        }
-
-        private List<MethodSignature> toUnmodifiableMethods(
-                final List<MethodSignatureBuilder> methodBuilders) {
-            final List<MethodSignature> methods = new ArrayList<MethodSignature>();
-            for (final MethodSignatureBuilder builder : methodBuilders) {
-                methods.add(builder.toInstance(this));
-            }
-            return Collections.unmodifiableList(methods);
+            this.properties = toUnmodifiableProperties(propBuilders);
+            this.equalsProperties = toUnmodifiableProperties(equalsBuilders);
+            this.hashCodeProperties = toUnmodifiableProperties(hashCodeBuilders);
+            this.stringProperties = toUnmodifiableProperties(stringBuilders);
         }
 
         private List<GeneratedProperty> toUnmodifiableProperties(
                 final List<GeneratedPropertyBuilder> propBuilders) {
-            final List<GeneratedProperty> constants = new ArrayList<GeneratedProperty>();
+            final List<GeneratedProperty> properties = new ArrayList<>();
             for (final GeneratedPropertyBuilder builder : propBuilders) {
-                constants.add(builder.toInstance(this));
+                properties.add(builder.toInstance(this));
             }
-            return Collections.unmodifiableList(constants);
-        }
-
-        @Override
-        public String getPackageName() {
-            return packageName;
-        }
-
-        @Override
-        public String getName() {
-            return name;
-        }
-
-        @Override
-        public Type getParentType() {
-            return null;
-        }
-
-        @Override
-        public String getComment() {
-            return comment;
-        }
-
-        @Override
-        public List<AnnotationType> getAnnotations() {
-            return annotations;
-        }
-
-        @Override
-        public List<Type> getImplements() {
-            return implementsTypes;
+            return Collections.unmodifiableList(properties);
         }
 
         @Override
@@ -532,21 +165,6 @@ public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
             return extendsType;
         }
 
-        @Override
-        public List<Enumeration> getEnumDefintions() {
-            return enumerations;
-        }
-
-        @Override
-        public List<Constant> getConstantDefinitions() {
-            return constants;
-        }
-
-        @Override
-        public List<MethodSignature> getMethodDefinitions() {
-            return methods;
-        }
-
         @Override
         public List<GeneratedProperty> getProperties() {
             return properties;
@@ -567,58 +185,27 @@ public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
             return stringProperties;
         }
 
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((name == null) ? 0 : name.hashCode());
-            result = prime * result
-                    + ((packageName == null) ? 0 : packageName.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            GeneratedTransferObjectImpl other = (GeneratedTransferObjectImpl) obj;
-            if (name == null) {
-                if (other.name != null) {
-                    return false;
-                }
-            } else if (!name.equals(other.name)) {
-                return false;
-            }
-            if (packageName == null) {
-                if (other.packageName != null) {
-                    return false;
-                }
-            } else if (!packageName.equals(other.packageName)) {
-                return false;
-            }
-            return true;
-        }
-
         @Override
         public String toString() {
             StringBuilder builder = new StringBuilder();
             builder.append("GeneratedTransferObject [packageName=");
-            builder.append(packageName);
+            builder.append(getPackageName());
             builder.append(", name=");
-            builder.append(name);
+            builder.append(getName());
             builder.append(", comment=");
-            builder.append(comment);
+            builder.append(", annotations=");
+            builder.append(getAnnotations());
+            builder.append(getComment());
+            builder.append(", extends=");
+            builder.append(getExtends());
+            builder.append(", implements=");
+            builder.append(getImplements());
+            builder.append(", enclosedTypes=");
+            builder.append(getEnclosedTypes());
             builder.append(", constants=");
-            builder.append(constants);
+            builder.append(getConstantDefinitions());
             builder.append(", enumerations=");
-            builder.append(enumerations);
+            builder.append(getEnumerations());
             builder.append(", properties=");
             builder.append(properties);
             builder.append(", equalsProperties=");
@@ -627,34 +214,10 @@ public class GeneratedTOBuilderImpl implements GeneratedTOBuilder {
             builder.append(hashCodeProperties);
             builder.append(", stringProperties=");
             builder.append(stringProperties);
-            builder.append(", annotations=");
-            builder.append(annotations);
             builder.append(", methods=");
-            builder.append(methods);
+            builder.append(getMethodDefinitions());
             builder.append("]");
             return builder.toString();
         }
     }
-
-    private static final class GeneratedTransferIdentityObjectImpl extends
-            GeneratedTransferObjectImpl implements
-            GeneratedTransferIdentityObject {
-        public GeneratedTransferIdentityObjectImpl(final String packageName,
-                final String name, final String comment,
-                final List<AnnotationTypeBuilder> annotationBuilders,
-                final GeneratedTransferObject extendsType,
-                final List<Type> implementsTypes,
-                final List<ConstantBuilder> constantBuilders,
-                final List<EnumBuilder> enumBuilders,
-                final List<MethodSignatureBuilder> methodBuilders,
-                final List<GeneratedPropertyBuilder> propBuilers,
-                final List<GeneratedPropertyBuilder> equalsBuilers,
-                final List<GeneratedPropertyBuilder> hashCodeBuilers,
-                final List<GeneratedPropertyBuilder> stringBuilers) {
-            super(packageName, name, comment, annotationBuilders, extendsType,
-                    implementsTypes, constantBuilders, enumBuilders,
-                    methodBuilders, propBuilers, equalsBuilers,
-                    hashCodeBuilers, stringBuilers);
-        }
-    }
 }
index 3a3ded39babc818b3abdf57008307399e3ac4780..a3ffbda4f55adc64d93dc505e6ed462b2cc253c1 100644 (file)
  */
 package org.opendaylight.controller.binding.generator.util.generated.type.builder;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
 import org.opendaylight.controller.sal.binding.model.api.Constant;
-import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
-import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.ConstantBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
-
-public final class GeneratedTypeBuilderImpl implements GeneratedTypeBuilder {
-
-    private final String packageName;
-    private String comment = "";
-    private final String name;
-    private final List<AnnotationTypeBuilder> annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
-    private final List<Type> implementsTypes = new ArrayList<Type>();
-    private final List<EnumBuilder> enumDefinitions = new ArrayList<EnumBuilder>();
-    private final List<ConstantBuilder> constantDefintions = new ArrayList<ConstantBuilder>();
-    private final List<MethodSignatureBuilder> methodDefinitions = new ArrayList<MethodSignatureBuilder>();
-    
-    public GeneratedTypeBuilderImpl(final String packageName, final String name) {
-        this.packageName = packageName;
-        this.name = name;
-    }
-
-    @Override
-    public Type getParentType() {
-        return this;
-    }
-
-    @Override
-    public String getPackageName() {
-        return packageName;
-    }
-
-    @Override
-    public String getName() {
-        return name;
-    }
-
-    @Override
-    public void addComment(String comment) {
-        this.comment = comment;
-    }
+import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
 
-    @Override
-    public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
-        if (packageName != null && name != null) {
-            final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
-                    packageName, name);
-            if (annotationBuilders.add(builder)) {
-                return builder;
-            }
-        }
-        return null;
-    }
+import java.util.List;
 
-    @Override
-    public ConstantBuilder addConstant(Type type, String name, Object value) {
-        final ConstantBuilder builder = new ConstantBuilderImpl(type, name,
-                value);
-        constantDefintions.add(builder);
-        return builder;
-    }
+public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder {
 
-    @Override
-    public EnumBuilder addEnumeration(final String name) {
-        final String innerPackageName = packageName + "." + this.name;
-        final EnumBuilder builder = new EnumerationBuilderImpl(
-                innerPackageName, name);
-        enumDefinitions.add(builder);
-        return builder;
+    public GeneratedTypeBuilderImpl(String packageName, String name) {
+        super(packageName, name);
+        setAbstract(true);
     }
 
     @Override
-    public MethodSignatureBuilder addMethod(final String name) {
-        final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(
-                this, name);
-        methodDefinitions.add(builder);
-        return builder;
+    public GeneratedType toInstance() {
+        return new GeneratedTypeImpl(null, getPackageName(), getName(), getComment(), getAnnotations(), isAbstract(),
+                getImplementsTypes(), getEnclosedTypes(), getEnclosedTransferObjects(), getEnumerations(),
+                getConstants(), getMethodDefinitions());
     }
 
     @Override
-    public boolean addImplementsType(final Type genType) {
-        if (genType != null) {
-            return implementsTypes.add(genType);
-        }
-        return false;
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("GeneratedTransferObject [packageName=");
+        builder.append(getPackageName());
+        builder.append(", name=");
+        builder.append(getName());
+        builder.append(", comment=");
+        builder.append(", annotations=");
+        builder.append(getAnnotations());
+        builder.append(getComment());
+        builder.append(", implements=");
+        builder.append(getImplementsTypes());
+        builder.append(", enclosedTypes=");
+        builder.append(getEnclosedTypes());
+        builder.append(", constants=");
+        builder.append(getConstants());
+        builder.append(", enumerations=");
+        builder.append(getEnumerations());
+        builder.append(", properties=");
+        builder.append(", methods=");
+        builder.append(getMethodDefinitions());
+        builder.append("]");
+        return builder.toString();
     }
-    
-    @Override
-    public GeneratedType toInstance() {
-        return new GeneratedTypeImpl(this, packageName, name, comment,
-                annotationBuilders, implementsTypes, enumDefinitions, constantDefintions,
-                methodDefinitions);
-    }
-    
-    private static final class GeneratedTypeImpl implements GeneratedType {
-
-        private final Type parent;
-        private final String packageName;
-        private final String name;
-        private final String comment;
-        private final List<AnnotationType> annotations;
-        private final List<Type> implementsTypes;
-        private final List<Enumeration> enumDefinitions;
-        private final List<Constant> constantDefintions;
-        private final List<MethodSignature> methodDefinitions;
-
-        public GeneratedTypeImpl(final Type parent, final String packageName,
-                final String name, final String comment,
-                final List<AnnotationTypeBuilder> annotationBuilders,
-                final List<Type> implementsTypes,
-                final List<EnumBuilder> enumBuilders,
-                final List<ConstantBuilder> constantBuilders,
-                final List<MethodSignatureBuilder> methodBuilders) {
-            super();
-            this.parent = parent;
-            this.packageName = packageName;
-            this.name = name;
-            this.comment = comment;
-            this.annotations = toUnmodifiableAnnotations(annotationBuilders);
-            this.implementsTypes = Collections.unmodifiableList(implementsTypes); 
-            this.constantDefintions = toUnmodifiableConstants(constantBuilders);
-            this.enumDefinitions = toUnmodifiableEnums(enumBuilders);
-            this.methodDefinitions = toUnmodifiableMethods(methodBuilders);
-        }
-
-        private List<AnnotationType> toUnmodifiableAnnotations(
-                final List<AnnotationTypeBuilder> annotationBuilders) {
-            final List<AnnotationType> annotations = new ArrayList<AnnotationType>();
-            for (final AnnotationTypeBuilder builder : annotationBuilders) {
-                annotations.add(builder.toInstance());
-            }
-            return Collections.unmodifiableList(annotations);
-        }
-
-        private List<MethodSignature> toUnmodifiableMethods(
-                List<MethodSignatureBuilder> methodBuilders) {
-            final List<MethodSignature> methods = new ArrayList<MethodSignature>();
-            for (final MethodSignatureBuilder methodBuilder : methodBuilders) {
-                methods.add(methodBuilder.toInstance(this));
-            }
-            return Collections.unmodifiableList(methods);
-        }
-
-        private List<Enumeration> toUnmodifiableEnums(
-                List<EnumBuilder> enumBuilders) {
-            final List<Enumeration> enums = new ArrayList<Enumeration>();
-            for (final EnumBuilder enumBuilder : enumBuilders) {
-                enums.add(enumBuilder.toInstance(this));
-            }
-            return Collections.unmodifiableList(enums);
-        }
-
-        private List<Constant> toUnmodifiableConstants(
-                List<ConstantBuilder> constantBuilders) {
-            final List<Constant> constants = new ArrayList<Constant>();
-            for (final ConstantBuilder enumBuilder : constantBuilders) {
-                constants.add(enumBuilder.toInstance(this));
-            }
-            return Collections.unmodifiableList(constants);
-        }
-
-        @Override
-        public String getPackageName() {
-            return packageName;
-        }
-
-        @Override
-        public String getName() {
-            return name;
-        }
-
-        @Override
-        public Type getParentType() {
-            return parent;
-        }
-
-        @Override
-        public String getComment() {
-            return comment;
-        }
-
-        @Override
-        public List<AnnotationType> getAnnotations() {
-            return annotations;
-        }
-        
-        @Override
-        public List<Type> getImplements() {
-            return implementsTypes;
-        }
-        
-        @Override
-        public List<Enumeration> getEnumDefintions() {
-            return enumDefinitions;
-        }
-
-        @Override
-        public List<Constant> getConstantDefinitions() {
-            return constantDefintions;
-        }
-
-        @Override
-        public List<MethodSignature> getMethodDefinitions() {
-            return methodDefinitions;
-        }
-
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime
-                    * result
-                    + ((constantDefintions == null) ? 0 : constantDefintions
-                            .hashCode());
-            result = prime
-                    * result
-                    + ((enumDefinitions == null) ? 0 : enumDefinitions
-                            .hashCode());
-            result = prime
-                    * result
-                    + ((methodDefinitions == null) ? 0 : methodDefinitions
-                            .hashCode());
-            result = prime * result + ((name == null) ? 0 : name.hashCode());
-            result = prime * result
-                    + ((packageName == null) ? 0 : packageName.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            GeneratedTypeImpl other = (GeneratedTypeImpl) obj;
-            if (constantDefintions == null) {
-                if (other.constantDefintions != null) {
-                    return false;
-                }
-            } else if (!constantDefintions.equals(other.constantDefintions)) {
-                return false;
-            }
-            if (enumDefinitions == null) {
-                if (other.enumDefinitions != null) {
-                    return false;
-                }
-            } else if (!enumDefinitions.equals(other.enumDefinitions)) {
-                return false;
-            }
-            if (methodDefinitions == null) {
-                if (other.methodDefinitions != null) {
-                    return false;
-                }
-            } else if (!methodDefinitions.equals(other.methodDefinitions)) {
-                return false;
-            }
-            if (name == null) {
-                if (other.name != null) {
-                    return false;
-                }
-            } else if (!name.equals(other.name)) {
-                return false;
-            }
-            if (packageName == null) {
-                if (other.packageName != null) {
-                    return false;
-                }
-            } else if (!packageName.equals(other.packageName)) {
-                return false;
-            }
-            return true;
-        }
 
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("GeneratedType [packageName=");
-            builder.append(packageName);
-            builder.append(", name=");
-            builder.append(name);
-            if (parent != null) {
-                builder.append(", parent=");
-                builder.append(parent.getPackageName());
-                builder.append(".");
-                builder.append(parent.getName());
-            } else {
-                builder.append(", parent=null");
-            }
-            builder.append(", comment=");
-            builder.append(comment);
-            builder.append(", annotations=");
-            builder.append(annotations);
-            builder.append(", enumDefinitions=");
-            builder.append(enumDefinitions);
-            builder.append(", constantDefintions=");
-            builder.append(constantDefintions);
-            builder.append(", methodDefinitions=");
-            builder.append(methodDefinitions);
-            builder.append("]");
-            return builder.toString();
+    private static final class GeneratedTypeImpl extends AbstractGeneratedType {
+
+        public GeneratedTypeImpl(final Type parent, final String packageName, final String name, final String comment,
+                                 final List<AnnotationTypeBuilder> annotationBuilders, final boolean isAbstract,
+                                 final List<Type> implementsTypes,
+                                 final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+                                 final List<GeneratedTOBuilder> enclosedGenTOBuilders,
+                                 final List<EnumBuilder> enumBuilders, final List<Constant> constants,
+                                 final List<MethodSignatureBuilder> methodBuilders) {
+            super(parent, packageName, name, comment, annotationBuilders, isAbstract, implementsTypes,
+                    enclosedGenTypeBuilders, enclosedGenTOBuilders, enumBuilders, constants, methodBuilders);
         }
     }
 }
index a2ce27c72a54e746094aac07059dac79eab1a6af..ebb68647bfe8d9206e27500494f08e95e26fec06 100644 (file)
@@ -1,49 +1,34 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.binding.generator.util.generated.type.builder;
 
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
 
-import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
 import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
 import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
 
-final class MethodSignatureBuilderImpl implements MethodSignatureBuilder {
-    private final String name;
-    private Type returnType;
+final class MethodSignatureBuilderImpl extends AbstractTypeMemberBuilder implements MethodSignatureBuilder {
+
     private final List<MethodSignature.Parameter> parameters;
-    private final List<AnnotationTypeBuilder> annotationBuilders;
-    private String comment = "";
-    private final Type parent;
+    private boolean isAbstract;
 
-    public MethodSignatureBuilderImpl(final Type parent, final String name) {
-        super();
-        this.name = name;
-        this.parent = parent;
-        this.parameters = new ArrayList<MethodSignature.Parameter>();
-        this.annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
+    public MethodSignatureBuilderImpl(final String name) {
+        super(name);
+        this.parameters = new ArrayList<>();
     }
 
     @Override
-    public AnnotationTypeBuilder addAnnotation(String packageName, String name) {
-        if (packageName != null && name != null) {
-            final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(
-                    packageName, name);
-            if (annotationBuilders.add(builder)) {
-                return builder;
-            }
-        }
-        return null;
-    }
-
-    @Override
-    public void addReturnType(Type returnType) {
-        if (returnType != null) {
-            this.returnType = returnType;
-        }
+    public void setAbstract(boolean isAbstract) {
+        this.isAbstract = isAbstract;
     }
 
     @Override
@@ -51,26 +36,22 @@ final class MethodSignatureBuilderImpl implements MethodSignatureBuilder {
         parameters.add(new MethodParameterImpl(name, type));
     }
 
-    @Override
-    public void addComment(String comment) {
-        this.comment = comment;
-    }
-
     @Override
     public MethodSignature toInstance(Type definingType) {
-        return new MethodSignatureImpl(definingType, name, annotationBuilders,
-                comment, returnType, parameters);
+        final List<AnnotationType> annotations = toAnnotationTypes();
+        return new MethodSignatureImpl(definingType, getName(), annotations,
+                getComment(), getAccessModifier(), getReturnType(), parameters, isFinal(), isAbstract);
     }
     
     @Override
     public int hashCode() {
         final int prime = 31;
         int result = 1;
-        result = prime * result + ((name == null) ? 0 : name.hashCode());
+        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
         result = prime * result
                 + ((parameters == null) ? 0 : parameters.hashCode());
         result = prime * result
-                + ((returnType == null) ? 0 : returnType.hashCode());
+                + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
         return result;
     }
 
@@ -86,11 +67,11 @@ final class MethodSignatureBuilderImpl implements MethodSignatureBuilder {
             return false;
         }
         MethodSignatureBuilderImpl other = (MethodSignatureBuilderImpl) obj;
-        if (name == null) {
-            if (other.name != null) {
+        if (getName() == null) {
+            if (other.getName() != null) {
                 return false;
             }
-        } else if (!name.equals(other.name)) {
+        } else if (!getName().equals(other.getName())) {
             return false;
         }
         if (parameters == null) {
@@ -100,11 +81,11 @@ final class MethodSignatureBuilderImpl implements MethodSignatureBuilder {
         } else if (!parameters.equals(other.parameters)) {
             return false;
         }
-        if (returnType == null) {
-            if (other.returnType != null) {
+        if (getReturnType() == null) {
+            if (other.getReturnType() != null) {
                 return false;
             }
-        } else if (!returnType.equals(other.returnType)) {
+        } else if (!getReturnType().equals(other.getReturnType())) {
             return false;
         }
         return true;
@@ -114,160 +95,16 @@ final class MethodSignatureBuilderImpl implements MethodSignatureBuilder {
     public String toString() {
         StringBuilder builder = new StringBuilder();
         builder.append("MethodSignatureBuilderImpl [name=");
-        builder.append(name);
+        builder.append(getName());
         builder.append(", returnType=");
-        builder.append(returnType);
+        builder.append(getReturnType());
         builder.append(", parameters=");
         builder.append(parameters);
         builder.append(", annotationBuilders=");
-        builder.append(annotationBuilders);
+        builder.append(getAnnotationBuilders());
         builder.append(", comment=");
-        builder.append(comment);
-        if (parent != null) {
-            builder.append(", parent=");
-            builder.append(parent.getPackageName());
-            builder.append(".");
-            builder.append(parent.getName());
-        } else {
-            builder.append(", parent=null");
-        }
+        builder.append(getComment());
         builder.append("]");
         return builder.toString();
     }
-
-    private static final class MethodSignatureImpl implements MethodSignature {
-
-        private final String name;
-        private final String comment;
-        private final Type definingType;
-        private final Type returnType;
-        private final List<Parameter> params;
-        private List<AnnotationType> annotations;
-
-        public MethodSignatureImpl(final Type definingType, final String name,
-                final List<AnnotationTypeBuilder> annotationBuilders,
-                final String comment, final Type returnType,
-                final List<Parameter> params) {
-            super();
-            this.name = name;
-            this.comment = comment;
-            this.definingType = definingType;
-            this.returnType = returnType;
-            this.params = Collections.unmodifiableList(params);
-            
-            this.annotations = new ArrayList<AnnotationType>();
-            for (final AnnotationTypeBuilder builder : annotationBuilders) {
-                this.annotations.add(builder.toInstance());
-            }
-            this.annotations = Collections.unmodifiableList(this.annotations);
-        }
-
-        @Override
-        public List<AnnotationType> getAnnotations() {
-            return annotations;
-        }
-
-        @Override
-        public String getName() {
-            return name;
-        }
-
-        @Override
-        public String getComment() {
-            return comment;
-        }
-
-        @Override
-        public Type getDefiningType() {
-            return definingType;
-        }
-
-        @Override
-        public Type getReturnType() {
-            return returnType;
-        }
-
-        @Override
-        public List<Parameter> getParameters() {
-            return params;
-        }
-
-        @Override
-        public AccessModifier getAccessModifier() {
-            return AccessModifier.PUBLIC;
-        }
-
-        @Override
-        public int hashCode() {
-            final int prime = 31;
-            int result = 1;
-            result = prime * result + ((name == null) ? 0 : name.hashCode());
-            result = prime * result
-                    + ((params == null) ? 0 : params.hashCode());
-            result = prime * result
-                    + ((returnType == null) ? 0 : returnType.hashCode());
-            return result;
-        }
-
-        @Override
-        public boolean equals(Object obj) {
-            if (this == obj) {
-                return true;
-            }
-            if (obj == null) {
-                return false;
-            }
-            if (getClass() != obj.getClass()) {
-                return false;
-            }
-            MethodSignatureImpl other = (MethodSignatureImpl) obj;
-            if (name == null) {
-                if (other.name != null) {
-                    return false;
-                }
-            } else if (!name.equals(other.name)) {
-                return false;
-            }
-            if (params == null) {
-                if (other.params != null) {
-                    return false;
-                }
-            } else if (!params.equals(other.params)) {
-                return false;
-            }
-            if (returnType == null) {
-                if (other.returnType != null) {
-                    return false;
-                }
-            } else if (!returnType.equals(other.returnType)) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override
-        public String toString() {
-            StringBuilder builder = new StringBuilder();
-            builder.append("MethodSignatureImpl [name=");
-            builder.append(name);
-            builder.append(", comment=");
-            builder.append(comment);
-            if (definingType != null) {
-                builder.append(", definingType=");
-                builder.append(definingType.getPackageName());
-                builder.append(".");
-                builder.append(definingType.getName());
-            } else {
-                builder.append(", definingType= null");
-            }
-            builder.append(", returnType=");
-            builder.append(returnType);
-            builder.append(", params=");
-            builder.append(params);
-            builder.append(", annotations=");
-            builder.append(annotations);
-            builder.append("]");
-            return builder.toString();
-        }
-    }
 }
\ No newline at end of file
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/MethodSignatureImpl.java b/opendaylight/sal/yang-prototype/code-generator/binding-generator-util/src/main/java/org/opendaylight/controller/binding/generator/util/generated/type/builder/MethodSignatureImpl.java
new file mode 100644 (file)
index 0000000..5be1cc9
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.binding.generator.util.generated.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+import java.util.Collections;
+import java.util.List;
+
+class MethodSignatureImpl extends AbstractTypeMember implements MethodSignature {
+
+    private final List<Parameter> params;
+    private final boolean isAbstract;
+
+    public MethodSignatureImpl(final Type definingType, final String name,
+                               final List<AnnotationType> annotations,
+                               final String comment, final AccessModifier accessModifier,
+                               final Type returnType, final List<Parameter> params, boolean isFinal,
+                               boolean isAbstract) {
+        super(definingType, name, annotations, comment, accessModifier, returnType, isFinal);
+        this.params = Collections.unmodifiableList(params);
+        this.isAbstract = isAbstract;
+    }
+
+    @Override
+    public boolean isAbstract() {
+        return isAbstract;
+    }
+
+    @Override
+    public List<Parameter> getParameters() {
+        return params;
+    }
+
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
+        result = prime * result
+                + ((params == null) ? 0 : params.hashCode());
+        result = prime * result
+                + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+        return result;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (obj == null) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        MethodSignatureImpl other = (MethodSignatureImpl) obj;
+        if (getName() == null) {
+            if (other.getName() != null) {
+                return false;
+            }
+        } else if (!getName().equals(other.getName())) {
+            return false;
+        }
+        if (params == null) {
+            if (other.params != null) {
+                return false;
+            }
+        } else if (!params.equals(other.params)) {
+            return false;
+        }
+        if (getReturnType() == null) {
+            if (other.getReturnType() != null) {
+                return false;
+            }
+        } else if (!getReturnType().equals(other.getReturnType())) {
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder builder = new StringBuilder();
+        builder.append("MethodSignatureImpl [name=");
+        builder.append(getName());
+        builder.append(", comment=");
+        builder.append(getComment());
+        if (getDefiningType() != null) {
+            builder.append(", definingType=");
+            builder.append(getDefiningType().getPackageName());
+            builder.append(".");
+            builder.append(getDefiningType().getName());
+        } else {
+            builder.append(", definingType= null");
+        }
+        builder.append(", returnType=");
+        builder.append(getReturnType());
+        builder.append(", params=");
+        builder.append(params);
+        builder.append(", annotations=");
+        builder.append(getAnnotations());
+        builder.append("]");
+        return builder.toString();
+    }
+}
index 107dc5910bc2ea24a5d06ea17339cac9baf06c93..0f2daa86c38f290973fc1b24bcb283b95e26e605 100644 (file)
@@ -17,7 +17,6 @@ import java.util.List;
 
 import org.junit.Test;
 import org.opendaylight.controller.binding.generator.util.Types;
-import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
 import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
@@ -76,7 +75,7 @@ public class AnnotationBuilderTest {
 
         final MethodSignatureBuilder methodBuilder = genTypeBuilder
                 .addMethod("simpleMethod");
-        methodBuilder.addReturnType(Types.typeForClass(Integer.class));
+        methodBuilder.setReturnType(Types.typeForClass(Integer.class));
         final AnnotationTypeBuilder annotManAttr = methodBuilder
                 .addAnnotation("org.springframework.jmx.export.annotation",
                         "ManagedAttribute");
@@ -142,7 +141,7 @@ public class AnnotationBuilderTest {
 
         final GeneratedPropertyBuilder propertyBuilder = genTOBuilder
                 .addProperty("simpleProperty");
-        propertyBuilder.addReturnType(Types.typeForClass(Integer.class));
+        propertyBuilder.setReturnType(Types.typeForClass(Integer.class));
         final AnnotationTypeBuilder annotManAttr = propertyBuilder
                 .addAnnotation("org.springframework.jmx.export.annotation",
                         "ManagedAttribute");
index aaeec40604a61c264afef7d23e5f7111b115a1ef..877bcfce630113940aadbc238fd2b7700f02911c 100644 (file)
@@ -30,7 +30,6 @@ public final class ClassCodeGenerator implements CodeGenerator {
     @Override
     public Writer generate(Type type) throws IOException {
         final Writer writer = new StringWriter();
-        boolean isIdentity = type instanceof GeneratedTransferIdentityObject;
 
         if (type instanceof GeneratedTransferObject) {
             GeneratedTransferObject genTO = (GeneratedTransferObject) type;            
@@ -38,7 +37,7 @@ public final class ClassCodeGenerator implements CodeGenerator {
             
             final String currentPkg = genTO.getPackageName();
             final List<GeneratedProperty> fields = genTO.getProperties();
-            final List<Enumeration> enums = genTO.getEnumDefintions();
+            final List<Enumeration> enums = genTO.getEnumerations();
 
             writer.write(GeneratorUtil.createPackageDeclaration(currentPkg));
             writer.write(NL);
@@ -50,7 +49,7 @@ public final class ClassCodeGenerator implements CodeGenerator {
             writer.write(NL);
 
             writer.write(GeneratorUtil.createClassDeclaration(genTO, "",
-                    imports, isIdentity));
+                    imports, genTO.isAbstract()));
             writer.write(NL);
             writer.write(NL);
             
@@ -69,7 +68,7 @@ public final class ClassCodeGenerator implements CodeGenerator {
                 }
                 writer.write(NL);
                 writer.write(GeneratorUtil.createConstructor(genTO, TAB,
-                        imports, isIdentity) + NL);
+                        imports, genTO.isAbstract()) + NL);
                 writer.write(NL);
                 for (GeneratedProperty field : fields) {
                     writer.write(GeneratorUtil.createGetter(field, TAB,
index 5b3b17dbf6c73334fe471dd3e797f8a18e228749..804ac99ff26138d1e36d18c6dbbd99755fc1b946 100644 (file)
@@ -622,7 +622,7 @@ public final class GeneratorUtil {
         final String genTypePkg = genType.getPackageName();
 
         final List<Constant> constants = genType.getConstantDefinitions();
-        final List<MethodSignature> methods = genType.getMethodDefinitions();
+               final List<MethodSignature> methods = genType.getMethodDefinitions();
         List<Type> impl = genType.getImplements();
 
         // IMPLEMENTATIONS
index 38d3bcdc070dd4522a7c9d28ef28e2721bd10561..16d63efe1b527fe48d7da11cb468ab4bda54da7d 100644 (file)
@@ -82,7 +82,7 @@ public final class InterfaceGenerator implements CodeGenerator {
                        final List<Constant> constants = genType.getConstantDefinitions();
                        final List<MethodSignature> methods = genType
                                        .getMethodDefinitions();
-                       final List<Enumeration> enums = genType.getEnumDefintions();
+                       final List<Enumeration> enums = genType.getEnumerations();
 
                        writer.write(GeneratorUtil.createPackageDeclaration(genType
                                        .getPackageName()));
@@ -105,5 +105,4 @@ public final class InterfaceGenerator implements CodeGenerator {
                }
                return writer;
        }
-
 }
index 5dd011be32afe6849716b6279d0facd12673101a..8916131a3fe5bf5944a7598e826be249a6b02130 100644 (file)
@@ -110,11 +110,11 @@ public class ClassCodeGeneratorTest {
                 "simple.pack", "DefCtor");
 
         GeneratedPropertyBuilder propBuilder = toBuilder.addProperty("foo");
-        propBuilder.addReturnType(Types.typeForClass(String.class));
+        propBuilder.setReturnType(Types.typeForClass(String.class));
         propBuilder.setReadOnly(false);
 
         propBuilder = toBuilder.addProperty("bar");
-        propBuilder.addReturnType(Types.typeForClass(Integer.class));
+        propBuilder.setReturnType(Types.typeForClass(Integer.class));
         propBuilder.setReadOnly(false);
 
         final GeneratedTransferObject genTO = toBuilder.toInstance();
@@ -141,12 +141,12 @@ public class ClassCodeGeneratorTest {
                 "simple.pack", "DefCtor");
 
         GeneratedPropertyBuilder propBuilder = toBuilder.addProperty("foo");
-        propBuilder.addReturnType(Types.typeForClass(String.class));
+        propBuilder.setReturnType(Types.typeForClass(String.class));
         propBuilder.setReadOnly(false);
         toBuilder.addToStringProperty(propBuilder);
 
         propBuilder = toBuilder.addProperty("bar");
-        propBuilder.addReturnType(Types.typeForClass(Integer.class));
+        propBuilder.setReturnType(Types.typeForClass(Integer.class));
         propBuilder.setReadOnly(false);
         toBuilder.addToStringProperty(propBuilder);
         final GeneratedTransferObject genTO = toBuilder.toInstance();
index 5096dd88f8837e82e5b9f31155ad29022fdc0d30..52529e254e79a1648e72952be3bb89ee485d06c5 100644 (file)
@@ -7,6 +7,10 @@
  */\r
 package org.opendaylight.controller.sal.binding.model.api;\r
 \r
+/**\r
+ * Enum definition which provides four access modifiers that are described\r
+ * in Java programming language (Default, Private, Protected, Public).\r
+ */\r
 public enum AccessModifier {\r
-    PRIVATE, PUBLIC, PROTECTED\r
+    DEFAULT, PRIVATE, PUBLIC, PROTECTED\r
 }\r
index 7868675b1e6a40a21d6e14964a0ed218562a8a49..eec0339d0f17f32bfb03308b599fc7635614e02d 100644 (file)
@@ -9,25 +9,94 @@ package org.opendaylight.controller.sal.binding.model.api;
 
 import java.util.List;
 
-
+/**
+ * The Annotation Type interface is designed to hold information about
+ * annotation for any type that could be annotated in Java.
+ * <br>
+ * For sake of simplicity the Annotation Type is not designed to model exact
+ * behaviour of annotation mechanism, but just to hold information needed to
+ * model annotation over java Type definition.
+ */
 public interface AnnotationType extends Type {
-    
+
+    /**
+     * Returns the List of Annotations.
+     * <br>
+     * Each Annotation Type MAY have defined multiple Annotations.
+     *
+     * @return the List of Annotations.
+     */
     public List<AnnotationType> getAnnotations();
-    
+
+    /**
+     * Returns Parameter Definition assigned for given parameter name.
+     * <br>
+     * If Annotation does not contain parameter with specified param name,
+     * the method MAY return <code>null</code> value.
+     *
+     * @param paramName Parameter Name
+     * @return Parameter Definition assigned for given parameter name.
+     */
     public Parameter getParameter(final String paramName);
-    
+
+    /**
+     * Returns List of all parameters assigned to Annotation Type.
+     *
+     * @return List of all parameters assigned to Annotation Type.
+     */
     public List<Parameter> getParameters();
-    
+
+    /**
+     * Returns List of parameter names.
+     *
+     * @return List of parameter names.
+     */
     public List<String> getParameterNames();
-    
+
+    /**
+     * Returns <code>true</code> if annotation contains parameters.
+     *
+     * @return <code>true</code> if annotation contains parameters.
+     */
     public boolean containsParameters();
-    
+
+    /**
+     * Annotation Type parameter interface. For simplicity the Parameter
+     * contains values and value types as Strings. Every annotation which
+     * contains parameters could contain either single parameter or array of
+     * parameters. To model this purposes the by contract if the parameter
+     * contains single parameter the {@link #getValues()} method will return
+     * empty List and {@link #getValue()} MUST always return non-<code>null</code>
+     * parameter. If the Parameter holds List of values the singular {@link
+     * #getValue()} parameter MAY return <code>null</code> value.
+     */
     interface Parameter {
-        
+
+        /**
+         * Returns the Name of the parameter.
+         *
+         * @return the Name of the parameter.
+         */
         public String getName();
-        
+
+        /**
+         * Returns value in String format if Parameter contains singular value,
+         * otherwise MAY return <code>null</code>.
+         *
+         * @return value in String format if Parameter contains singular value.
+         */
         public String getValue();
-        
+
+        /**
+         * Returns List of Parameter assigned values in order in which they
+         * were assigned for given parameter name.
+         * <br>
+         * If there are multiple values assigned for given parameter name the
+         * method MUST NOT return empty List.
+         *
+         * @return List of Parameter assigned values in order in which they
+         * were assigned for given parameter name.
+         */
         public List<String> getValues();
     }
 }
index abde0da5e743a46d356de7738b4147038cfbc72b..092efc066b0fea703f8f32b026a262e812a592ca 100644 (file)
@@ -10,8 +10,18 @@ package org.opendaylight.controller.sal.binding.model.api;
 import java.io.IOException;\r
 import java.io.Writer;\r
 \r
+/**\r
+ *\r
+ *\r
+ */\r
 public interface CodeGenerator {\r
 \r
+    /**\r
+     *\r
+     * @param type\r
+     * @return\r
+     * @throws IOException\r
+     */\r
     Writer generate(Type type) throws IOException;\r
 \r
 }\r
index cad3460913d3d178759936dd67a9ea6c29a445e9..921a4733410a0a32e93de193f24245abeaa82682 100644 (file)
@@ -7,15 +7,61 @@
  */\r
 package org.opendaylight.controller.sal.binding.model.api;\r
 \r
+/**\r
+ * Interface Contact is designed to hold and model java constant. In Java\r
+ * there are no constant keywords instead of the constant is defined as\r
+ * static final field with assigned value. For this purpose the Constant\r
+ * interface contains methods {@link #getType()} to provide wrapped return\r
+ * Type of Constant, {@link #getName()} the Name of constant and the {@link\r
+ * #getValue()} for providing of value assigned to Constant. To determine of\r
+ * which type the constant value is it is recommended firstly to retrieve\r
+ * Type from constant. The Type interface holds base information like java\r
+ * package name and java type name (e.g. fully qualified name). From this\r
+ * string user should be able to determine to which type can be {@link\r
+ * #getValue()} type typecasted to unbox and provide value assigned to\r
+ * constant.\r
+ */\r
 public interface Constant {\r
 \r
+    /**\r
+     * Returns the Type that declares constant.\r
+     *\r
+     * @return the Type that declares constant.\r
+     */\r
     public Type getDefiningType();\r
 \r
+    /**\r
+     * Returns the return Type (or just Type) of the Constant.\r
+     *\r
+     * @return the return Type (or just Type) of the Constant.\r
+     */\r
     public Type getType();\r
 \r
+    /**\r
+     * Returns the name of constant.\r
+     * <br>\r
+     * By conventions the name SHOULD be in CAPITALS separated with\r
+     * underscores.\r
+     *\r
+     * @return the name of constant.\r
+     */\r
     public String getName();\r
 \r
+    /**\r
+     * Returns boxed value that is assigned for context.\r
+     *\r
+     * @return boxed value that is assigned for context.\r
+     */\r
     public Object getValue();\r
 \r
+    /**\r
+     * Returns Constant definition in formatted string.\r
+     * <br>\r
+     * <br>\r
+     * The expected string SHOULD be in format: <code>public final\r
+     * static [Type] CONSTANT_NAME = [value];</code>\r
+     *\r
+     * @return Constant definition in formatted string.\r
+     */\r
     public String toFormattedString();\r
 }\r
index 996423bb1bf67e35a7396a25b89a26fa90ed6f19..4115424ac835624014e9f2fd75c6ff0a971b580a 100644 (file)
@@ -9,16 +9,38 @@ package org.opendaylight.controller.sal.binding.model.api;
 
 import java.util.List;
 
+/**
+ *
+ */
 public interface Enumeration extends Type {
-    
+
+    /**
+     *
+     * @return
+     */
     public List<AnnotationType> getAnnotations();
-    
+
+    /**
+     *
+     * @return
+     */
     public Type getDefiningType();
 
+    /**
+     *
+     * @return
+     */
     public List<Pair> getValues();
 
+    /**
+     *
+     * @return
+     */
     public String toFormattedString();
 
+    /**
+     *
+     */
     interface Pair {
 
         public String getName();
index 462e1e1f63c5050b077c7fd13bdd673b2f498be0..119823d7a4054ba39845be4487e2d85b07b5dea3 100644 (file)
@@ -7,9 +7,24 @@
  */\r
 package org.opendaylight.controller.sal.binding.model.api;\r
 \r
-public interface GeneratedProperty extends MethodSignature {\r
+/**\r
+ * Generated Property extends interface {@link MethodSignature} interface.\r
+ * <br>\r
+ * The Generated Property interface is designed to store information of\r
+ * fields (or members) declared in Java Transfer Objects (or any java\r
+ * classes) and their access counterparts (getters and setters).\r
+ *\r
+ * @see MethodSignature\r
+ */\r
+public interface GeneratedProperty extends TypeMember {\r
 \r
+    /**\r
+     * Returns <code>true</code> if the property si declared as read-only.\r
+     * <br>\r
+     * If the property has flag <code>isReadOnly == true</code> the property\r
+     * SHOULD be generated as getter only.\r
+     *\r
+     * @return <code>true</code> if the property si declared as read-only.\r
+     */\r
     public boolean isReadOnly();\r
-\r
-    public boolean isFinal();\r
 }\r
index 6fa551e82122095cdcc86d06d756b2526c011ee6..e92dc77eee2a4f669679ab36e484ec7fefd9b3f2 100644 (file)
@@ -9,15 +9,64 @@ package org.opendaylight.controller.sal.binding.model.api;
 
 import java.util.List;
 
+/**
+ * Generated Transfer Object extends {@link GeneratedType} and is designed to
+ * represent Java Class. The Generated Transfer Object contains declarations
+ * of member fields stored in List of Properties. The Generated Transfer
+ * Object can be extended by exactly ONE Generated Transfer Object as Java
+ * don't allow multiple inheritance. For retrieval of implementing Generated
+ * Types use {@link #getImplements()} method.
+ * <br>
+ * Every transfer object SHOULD contain equals, hashCode and toString definitions.
+ * For this purpose retrieve definitions through {@link #getEqualsIdentifiers
+ * ()}, {@link #getHashCodeIdentifiers()} and {@link #getToStringIdentifiers
+ * ()}.
+ *
+ */
 public interface GeneratedTransferObject extends GeneratedType {
-    
+
+    /**
+     * Returns the extending Generated Transfer Object or <code>null</code>
+     * if there is no extending Generated Transfer Object.
+     *
+     * @return the extending Generated Transfer Object or <code>null</code>
+     * if there is no extending Generated Transfer Object.
+     */
     public GeneratedTransferObject getExtends();
-    
+
+    /**
+     * Returns List of Properties that are declared for Generated Transfer
+     * Object.
+     *
+     * @return List of Properties that are declared for Generated Transfer
+     * Object.
+     */
     public List<GeneratedProperty> getProperties();
-    
+
+    /**
+     * Returns List of Properties that are designated to define equality for
+     * Generated Transfer Object.
+     *
+     * @return List of Properties that are designated to define equality for
+     * Generated Transfer Object.
+     */
     public List<GeneratedProperty> getEqualsIdentifiers();
-    
+
+    /**
+     * Returns List of Properties that are designated to define identity for
+     * Generated Transfer Object.
+     *
+     * @return List of Properties that are designated to define identity for
+     * Generated Transfer Object.
+     */
     public List<GeneratedProperty> getHashCodeIdentifiers();
-    
+
+    /**
+     * Returns List of Properties that will be members of toString definition
+     * for Generated Transfer Object.
+     *
+     * @return List of Properties that will be members of toString definition
+     * for Generated Transfer Object.
+     */
     public List<GeneratedProperty> getToStringIdentifiers();
 }
index 82d1720714eaeee707a7ebf8b7fe2e809decb653..7a1a8f4f27d948ec5428445e0c61cc5fdfc1bc33 100644 (file)
@@ -16,6 +16,12 @@ import java.util.List;
  * <li><code>interface</code> name (with commentary that <b>SHOULD</b> be
  * present to proper define interface and base <i>contracts</i> specified for
  * interface)</li>
+ * <li>Each Generated Type can define list of types that Generated Type
+ * can implement to extend it's definition (i.e. interface extends list of
+ * interfaces or java class implements list of interfaces)</li>
+ * <li>Each Generated Type can contain multiple enclosed definitions of
+ * Generated Types (i.e. interface can contain N enclosed interface
+ * definitions or enclosed classes)</li>
  * <li><code>enum</code> and <code>constant</code> definitions (i.e. each
  * constant definition is by default defined as <code>public static final</code>
  * + type (either primitive or object) and constant name</li>
@@ -23,40 +29,76 @@ import java.util.List;
  * types) and return values</li>
  * </ul>
  * 
- * By the definition of the interface constant, enum and method definitions MUST
+ * By the definition of the interface constant, enum,
+ * enclosed types and method definitions MUST
  * be public, so there is no need to specify the scope of visibility.
- * 
- * 
  */
 public interface GeneratedType extends Type {
 
+    /**
+     * Returns the parent type if Generated Type is defined as enclosing type,
+     * otherwise returns <code>null</code>
+     *
+     * @return the parent type if Generated Type is defined as enclosing type,
+     * otherwise returns <code>null</code>
+     */
     public Type getParentType();
-    
+
+    /**
+     * Returns comment string associated with Generated Type.
+     *
+     * @return comment string associated with Generated Type.
+     */
     public String getComment();
-    
+
+    /**
+     * Returns List of annotation definitions associated with generated type.
+     *
+     * @return List of annotation definitions associated with generated type.
+     */
     public List<AnnotationType> getAnnotations();
-    
+
+    /**
+     * Returns <code>true</code> if The Generated Type is defined as abstract.
+     *
+     * @return <code>true</code> if The Generated Type is defined as abstract.
+     */
+    public boolean isAbstract();
+
+    /**
+     * Returns List of Types that Generated Type will implement.
+     *
+     * @return List of Types that Generated Type will implement.
+     */
     public List<Type> getImplements();
-    
+
     /**
-     * Returns Set of all Enumerator definitions associated with interface.
-     * 
-     * @return Set of all Enumerator definitions associated with interface.
+     * Returns List of enclosing Generated Types.
+     *
+     * @return List of enclosing Generated Types.
      */
-    public List<Enumeration> getEnumDefintions();
+    public List<GeneratedType> getEnclosedTypes();
 
     /**
+     * Returns List of all Enumerator definitions associated with Generated
+     * Type.
      * 
-     * 
-     * @return
+     * @return List of all Enumerator definitions associated with Generated
+     * Type.
+     */
+    public List<Enumeration> getEnumerations();
+
+    /**
+     * Returns List of Constant definitions associated with Generated Type.
+     *
+     * @return List of Constant definitions associated with Generated Type.
      */
     public List<Constant> getConstantDefinitions();
 
     /**
+     * Returns List of Method Definitions associated with Generated Type.
      * 
-     * 
-     * @return
+     * @return List of Method Definitions associated with Generated Type.
      */
     public List<MethodSignature> getMethodDefinitions();
-
 }
index dda1f01291c17ab5bb5e4572f09c25f6ffaa107c..88542e86f2c9f714f8f02a8f97bfe1366edc9338 100644 (file)
@@ -9,25 +9,62 @@ package org.opendaylight.controller.sal.binding.model.api;
 
 import java.util.List;
 
-public interface MethodSignature {
-    
-    public List<AnnotationType> getAnnotations();
-    
-    public String getName();
-
-    public String getComment();
-
-    public Type getDefiningType();
+/**
+ * The Method Signature interface contains simplified meta model for java
+ * method definition. Each method MUST be defined by name, return type,
+ * parameters and access modifier.
+ * <br>
+ * Additionally method MAY contain associated annotations and comment. By
+ * contract if method does not contain any comments or annotation definitions
+ * the {@link #getComment()} SHOULD rather return empty string and {@link
+ * #getAnnotations()} SHOULD rather return empty list than <code>null</code>
+ * values.
+ * <br>
+ * The defining Type contains the reference to Generated Type that declares
+ * Method Signature.
+ */
+public interface MethodSignature extends TypeMember {
 
-    public Type getReturnType();
+    /**
+     * Returns <code>true</code> if the method signature is defined as abstract.
+     * <br>
+     * By default in java all method declarations in interface are defined as abstract,
+     * but the user don't need necessary to declare abstract keyword in front of each method.
+     * <br>
+     * The abstract methods are allowed in Class definitions but only when the class is declared as abstract.
+     *
+     * @return <code>true</code> if the method signature is defined as abstract.
+     */
+    public boolean isAbstract();
 
+    /**
+     * Returns the List of parameters that method declare. If the method does
+     * not contain any parameters, the method will return empty List.
+     *
+     * @return the List of parameters that method declare.
+     */
     public List<Parameter> getParameters();
 
-    public AccessModifier getAccessModifier();
-
+    /**
+     * The Parameter interface is designed to hold the information of method
+     * Parameter(s). The parameter is defined by his Name which MUST be
+     * unique as java does not allow multiple parameters with same names for
+     * one method and Type that is associated with parameter.
+     */
     interface Parameter {
+
+        /**
+         * Returns the parameter name.
+         *
+         * @return the parameter name.
+         */
         public String getName();
 
+        /**
+         * Returns Type that is bounded to parameter name.
+         *
+         * @return Type that is bounded to parameter name.
+         */
         public Type getType();
     }
 }
index 1e800acaa926cc30842e460609042af9edf03c7e..86c4f5af04ccb6bd9e13ba95bddf301aca60a56f 100644 (file)
@@ -9,10 +9,29 @@ package org.opendaylight.controller.sal.binding.model.api;
 \r
 /**\r
  * Represents an instance of simple parametrized type such as List<String>.\r
+ *\r
+ * The parametrized Type is designed to be used to store information of Java\r
+ * Generic Type. The array of {@link #getActualTypeArguments()} holds\r
+ * information of all generic parameters defined for Parameterized Type.\r
  */\r
 public interface ParameterizedType extends Type {\r
 \r
+    /**\r
+     * Returns array of Types that are defined for Parameterized Type.\r
+     * <br>\r
+     * (for example if ParameterizedType encapsulates java generic Map that\r
+     * specifies two parameters Map<K,V> and the K is java.lang.Integer and V\r
+     * is defined as GeneratedType the array will contain two Types to store\r
+     * the information of generic parameters.)\r
+     *\r
+     * @return array of Types that are defined for Parameterized Type.\r
+     */\r
     Type[] getActualTypeArguments();\r
 \r
+    /**\r
+     * Returns the Raw Type definition of Parameterized Type.\r
+     *\r
+     * @return the Raw Type definition of Parameterized Type.\r
+     */\r
     Type getRawType();\r
 }\r
index 1ec3c9fab2e06da547a256f840846f03be87896e..c564ab46e4740a42150627d59bef7a63386d5f9a 100644 (file)
@@ -7,6 +7,13 @@
  */\r
 package org.opendaylight.controller.sal.binding.model.api;\r
 \r
+/**\r
+ * The Type interface defines the base type for all types defined in java.\r
+ * Each Type defined in java MUST contain name and package name,\r
+ * except of primitive types like int, byte etc. In case of mapping of\r
+ * primitive type the package name MUST be left as empty string.\r
+ *\r
+ */\r
 public interface Type {\r
     /**\r
      * Returns name of the package that interface belongs to.\r
@@ -21,4 +28,19 @@ public interface Type {
      * @return name of the interface.\r
      */\r
     public String getName();\r
+\r
+    /**\r
+     * Returns fully qualified name of Type.\r
+     * <br>\r
+     * The fully qualified name of Type MUST be returned in following format:\r
+     * <ul>\r
+     *     <li>If does not contains package name: [type name] (e.g. int, byte,\r
+     *     byte[],...)</li>\r
+     *     <li>If Type contains package name: [package name].[type name]\r
+     *     (e.g java.lang.Byte, org.opendaylight.controller.gen.GenType)</li>\r
+     * </ul>\r
+     *\r
+     * @return fully qualified name of Type.\r
+     */\r
+    public String getFullyQualifiedName();\r
 }\r
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/TypeMember.java b/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/TypeMember.java
new file mode 100644 (file)
index 0000000..e2176ff
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.model.api;
+
+import java.util.List;
+
+public interface TypeMember {
+
+    /**
+     * Returns List of annotation definitions associated with generated type.
+     *
+     * @return List of annotation definitions associated with generated type.
+     */
+    public List<AnnotationType> getAnnotations();
+
+    /**
+     * Returns the name of method.
+     *
+     * @return the name of method.
+     */
+    public String getName();
+
+    /**
+     * Returns comment string associated with method.
+     *
+     * @return comment string associated with method.
+     */
+    public String getComment();
+
+    /**
+     * Returns the Type that declares method.
+     *
+     * @return the Type that declares method.
+     */
+    public Type getDefiningType();
+
+    /**
+     * Returns the access modifier of method.
+     *
+     * @return the access modifier of method.
+     */
+    public AccessModifier getAccessModifier();
+
+    /**
+     * Returns the returning Type that methods returns.
+     *
+     * @return the returning Type that methods returns.
+     */
+    public Type getReturnType();
+
+    /**
+     * Returns <code>true</code> if method is declared as final.
+     *
+     * @return <code>true</code> if method is declared as final.
+     */
+    public boolean isFinal();
+}
index 6016274260f69aa8932be1ddc0815766bc862ac4..543c47b55d04a1bd33c0130a4ab6942f91688b1e 100644 (file)
@@ -12,13 +12,83 @@ import java.util.List;
 import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
+/**
+ * Annotation Type Builder Interface serves for creation and instantiation of
+ * immutable copy of Annotation Type. The Annotation Type Builder extends
+ * from {@link Type} interface. The Annotation Type contains set of methods
+ * which are capable to provide information about other Annotation Types and
+ * Annotation Parameters.
+ *
+ * @see AnnotationType
+ */
 public interface AnnotationTypeBuilder extends Type {
-    
+
+    /**
+     * The method creates new AnnotationTypeBuilder containing specified
+     * package name an annotation name.
+     * <br>
+     * Neither the package name or annotation name can contain
+     * <code>null</code> references. In case that
+     * any of parameters contains <code>null</code> the method SHOULD thrown
+     * {@link IllegalArgumentException}
+     *
+     * @param packageName Package Name of Annotation Type
+     * @param name Name of Annotation Type
+     * @return <code>new</code> instance of Annotation Type Builder.
+     */
     public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-    
+
+    /**
+     * Adds the parameter into List of parameters for Annotation Type.
+     * <br>
+     * If there is already stored parameter with the same name as the new
+     * parameter, the value of the old one will be simply overwritten by the
+     * newer parameter.
+     * <br>
+     * Neither the param name or value can contain
+     * <code>null</code> references. In case that
+     * any of parameters contains <code>null</code> the method SHOULD thrown
+     * {@link IllegalArgumentException}
+     *
+     * @param paramName Parameter Name
+     * @param value Parameter Value
+     * @return <code>true</code> if the parameter has been successfully
+     * assigned for Annotation Type
+     */
     public boolean addParameter(final String paramName, String value);
-    
+
+    /**
+     * Adds the parameter with specified List of parameter values into List of
+     * parameters for Annotation Type.
+     * <br>
+     * If there is already stored parameter with the same name as the new
+     * parameter, the value of the old one will be simply overwritten by the
+     * newer parameter.
+     * <br>
+     * Neither the param name or value can contain
+     * <code>null</code> references. In case that
+     * any of parameters contains <code>null</code> the method SHOULD thrown
+     * {@link IllegalArgumentException}
+     *
+     * @param paramName Parameter Name
+     * @param values List of Values bounded to Parameter Name
+     * @return <code>true</code> if the parameter has been successfully
+     * assigned for Annotation Type
+     */
     public boolean addParameters(final String paramName, List<String> values);
-    
+
+    /**
+     * Returns <code>new</code> <i>immutable</i> instance of Annotation Type
+     * with values assigned in current instance of Annotation Type Builder.
+     * <br>
+     * The return Annotation Type instance is immutable thus no additional
+     * modification to Annotation Type Builder will have an impact to
+     * instantiated Annotation Type.
+     * <br>
+     * For this purpose call this method after
+     * all additions are complete.
+     *
+     * @return <code>new</code> <i>immutable</i> instance of Annotation Type.
+     */
     public AnnotationType toInstance();
 }
index 9716c6053e40a88c9bb7019e36536ae4d874b4d6..5f3d84c1d622734c21d64aa04b20b798224a2f27 100644 (file)
@@ -11,14 +11,39 @@ import org.opendaylight.controller.sal.binding.model.api.Enumeration;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
 /**
-
+ * Enum Builder is interface that contains methods to build and instantiate
+ * Enumeration definition.
  *
+ * @see Enumeration
  */
 public interface EnumBuilder extends Type {
-    
+
+    /**
+     * The method creates new AnnotationTypeBuilder containing specified
+     * package name an annotation name.
+     * <br>
+     * Neither the package name or annotation name can contain
+     * <code>null</code> references. In case that
+     * any of parameters contains <code>null</code> the method SHOULD thrown
+     * {@link IllegalArgumentException}
+     *
+     * @param packageName Package Name of Annotation Type
+     * @param name Name of Annotation Type
+     * @return <code>new</code> instance of Annotation Type Builder.
+     */
     public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-    
+
+    /**
+     *
+     * @param name
+     * @param value
+     */
     public void addValue(final String name, final Integer value);
 
+    /**
+     *
+     * @param definingType
+     * @return
+     */
     public Enumeration toInstance(final Type definingType);
 }
index fd64cec8b79c0d41c9ab7ad5f9ea77f46bc36e56..f1df1fbc3b1d6e9b6db0e073ee97040f6c5b91ef 100644 (file)
@@ -7,29 +7,38 @@
   */
 package org.opendaylight.controller.sal.binding.model.api.type.builder;
 
-import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
 /**
-
+ * Generated Property Builder is interface that contains methods to build and
+ * instantiate Generated Property definition.
  *
+ * @see GeneratedProperty
  */
-public interface GeneratedPropertyBuilder {
-    
-    public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-    
-    public String getName();
-    
-    public boolean addReturnType(final Type returnType);
-    
-    public void accessorModifier(final AccessModifier modifier);
-    
-    public void addComment(final String comment);
-    
-    public void setFinal(final boolean isFinal);
-    
+public interface GeneratedPropertyBuilder extends TypeMemberBuilder {
+
+    /**
+     * Sets isReadOnly flag for property. If property is marked as read only
+     * it is the same as set property in java as final.
+     *
+     * @param isReadOnly Read Only property flag.
+     */
     public void setReadOnly(final boolean isReadOnly);
-    
+
+    /**
+     * Returns <code>new</code> <i>immutable</i> instance of Generated
+     * Property.
+     * <br>
+     * The <code>definingType</code> param cannot be <code>null</code>. The
+     * every member in Java MUST be declared and defined inside the scope of
+     * <code>class</code> definition. In case that
+     * defining Type will be passed as <code>null</code> reference the method
+     * SHOULD thrown {@link IllegalArgumentException}.
+     *
+     * @param definingType Defining Type of Generated Property
+     * @return <code>new</code> <i>immutable</i> instance of Generated
+     * Property.
+     */
     public GeneratedProperty toInstance(final Type definingType);
 }
index fc3495e184565f052f5b8a21a3f6577f1bac5e0f..8d36ad6c4635039798848e4dc5fdb1b27bb09be6 100644 (file)
@@ -10,23 +10,77 @@ package org.opendaylight.controller.sal.binding.model.api.type.builder;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
 
 /**
-
+ * Generated Transfer Object Builder is interface that contains methods to
+ * build and instantiate Generated Transfer Object definition.
+ *
+ * @see GeneratedTransferObject
  */
 public interface GeneratedTOBuilder extends GeneratedTypeBuilder {
 
-    public boolean addExtendsType(final GeneratedTransferObject genTransObj);
+    /**
+     * Add Generated Transfer Object from which will be extended current
+     * Generated Transfer Object.
+     * <br>
+     * By definition Java does not allow multiple
+     * inheritance, hence if there is already definition of Generated
+     * Transfer Object the extending object will be overwritten by lastly
+     * added Generated Transfer Object.
+     * <br>
+     * If Generated Transfer Object is <code>null</code> the method SHOULD
+     * throw {@link IllegalArgumentException}
+     *
+     * @param genTransObj Generated Transfer Object
+     */
+    public void setExtendsType(final GeneratedTransferObject genTransObj);
 
+    /**
+     * Add new Generated Property definition for Generated Transfer Object
+     * Builder and returns Generated Property Builder for specifying Property.
+     * <br>
+     * Name of Property cannot be <code>null</code>,
+     * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+     *
+     * @param name Name of Property
+     * @return <code>new</code> instance of Generated Property Builder.
+     */
     public GeneratedPropertyBuilder addProperty(final String name);
 
+    /**
+     * Add Property that will be part of <code>equals</code> definition.
+     * <br>
+     * If Generated Property Builder is <code>null</code> the method SHOULD
+     * throw {@link IllegalArgumentException}
+     *
+     * @param property Generated Property Builder
+     * @return <code>true</code> if addition of Generated Property into list
+     * of <code>equals</code> properties is successful.
+     */
     public boolean addEqualsIdentity(final GeneratedPropertyBuilder property);
 
+    /**
+     * Add Property that will be part of <code>hashCode</code> definition.
+     * <br>
+     * If Generated Property Builder is <code>null</code> the method SHOULD
+     * throw {@link IllegalArgumentException}
+     *
+     * @param property Generated Property Builder
+     * @return <code>true</code> if addition of Generated Property into list
+     * of <code>hashCode</code> properties is successful.
+     */
     public boolean addHashIdentity(final GeneratedPropertyBuilder property);
 
+    /**
+     * Add Property that will be part of <code>toString</code> definition.
+     * <br>
+     * If Generated Property Builder is <code>null</code> the method SHOULD
+     * throw {@link IllegalArgumentException}
+     *
+     * @param property Generated Property Builder
+     * @return <code>true</code> if addition of Generated Property into list
+     * of <code>toString</code> properties is successful.
+     */
     public boolean addToStringProperty(final GeneratedPropertyBuilder property);
 
     @Override
     public GeneratedTransferObject toInstance();
-
-    public GeneratedTransferObject toIdentityInstance();
-
 }
index 689e8311e2d30dd4b848fb2ff3f5275e5e8283cf..6bb58e0ca98b16d6046d5469bb8ac42e14dca0d4 100644 (file)
  */
 package org.opendaylight.controller.sal.binding.model.api.type.builder;
 
+import org.opendaylight.controller.sal.binding.model.api.Constant;
 import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
 /**
-
+ * Generated Type Builder interface is helper interface for building and
+ * defining the GeneratedType.
  *
+ * @see GeneratedType
  */
 public interface GeneratedTypeBuilder extends Type {
 
-    public Type getParentType();
+    /**
+     * Adds new Enclosing Type into definition of Generated Type and returns
+     * <code>new</code> Instance of Generated Type Builder.
+     * <br>
+     * There is no need of specifying of Package Name because enclosing Type
+     * is already defined inside Generated Type with specific package name.
+     * <br>
+     * The name of enclosing Type cannot be same as Name of parent type and
+     * if there is already defined enclosing type with the same name,
+     * the new enclosing type will simply overwrite the older definition.
+     * <br>
+     * If the name of enclosing type is <code>null</code> the method SHOULD
+     * throw {@link IllegalArgumentException}
+     *
+     * @param name Name of Enclosing Type
+     * @return <code>new</code> Instance of Generated Type Builder.
+     */
+    public GeneratedTypeBuilder addEnclosingType(final String name);
+
+    /**
+     * Adds new Enclosing Transfer Object into definition of Generated Type
+     * and returns <code>new</code> Instance of Generated TO Builder.
+     * <br>
+     * There is no need of specifying of Package Name because enclosing Type
+     * is already defined inside Generated Type with specific package name.
+     * <br>
+     * The name of enclosing Type cannot be same as Name of parent type and
+     * if there is already defined enclosing type with the same name,
+     * the new enclosing type will simply overwrite the older definition.
+     * <br>
+     * If the name of enclosing type is <code>null</code> the method SHOULD
+     * throw {@link IllegalArgumentException}
+     *
+     * @param name Name of Enclosing Type
+     * @return <code>new</code> Instance of Generated Type Builder.
+     */
+    public GeneratedTOBuilder addEnclosingTransferObject(final String name);
 
+    /**
+     * Adds String definition of comment into Method Signature definition.
+     * <br>
+     * The comment String MUST NOT contain anny comment specific chars (i.e.
+     * "/**" or "//") just plain String text description.
+     *
+     * @param comment Comment String.
+     */
     public void addComment(final String comment);
-    
+
+     /**
+     * The method creates new AnnotationTypeBuilder containing specified
+     * package name an annotation name.
+     * <br>
+     * Neither the package name or annotation name can contain
+     * <code>null</code> references. In case that
+     * any of parameters contains <code>null</code> the method SHOULD thrown
+     * {@link IllegalArgumentException}
+     *
+     * @param packageName Package Name of Annotation Type
+     * @param name Name of Annotation Type
+     * @return <code>new</code> instance of Annotation Type Builder.
+     */
     public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-    
+
+    /**
+     * Sets the <code>abstract</code> flag to define Generated Type as <i>abstract</i> type.
+     *
+     * @param isAbstract abstract flag
+     */
+    public void setAbstract(boolean isAbstract);
+
+    /**
+     * Add Type to implements.
+     *
+     * @param genType Type to implement
+     * @return <code>true</code> if the addition of type is successful.
+     */
     public boolean addImplementsType(final Type genType);
-    
-    public ConstantBuilder addConstant(final Type type, final String name,
+
+    /**
+     * Adds Constant definition and returns <code>new</code> Constant instance.
+     * <br>
+     * By definition Constant MUST be defined by return Type,
+     * Name and assigned value. The name SHOULD be defined with cpaital
+     * letters. Neither of method parameters can be <code>null</code> and the
+     * method SHOULD throw {@link IllegalArgumentException} if the contract
+     * is broken.
+     *
+     * @param type Constant Type
+     * @param name Name of Constant
+     * @param value Assigned Value
+     * @return <code>new</code> Constant instance.
+     */
+    public Constant addConstant(final Type type, final String name,
             final Object value);
 
+    /**
+     * Adds new Enumeration definition for Generated Type Builder and returns
+     * Enum Builder for specifying all Enum parameters.
+     * <br>
+     * If there is already Enumeration stored with the same name,
+     * the old enum will be simply overwritten byt new enum definition.
+     * <br>
+     * Name of Enumeration cannot be <code>null</code>,
+     * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+     *
+     * @param name Enumeration Name
+     * @return <code>new</code> instance of Enumeration Builder.
+     */
     public EnumBuilder addEnumeration(final String name);
 
+    /**
+     * Add new Method Signature definition for Generated Type Builder and
+     * returns Method Signature Builder for specifying all Method parameters.
+     * <br>
+     * Name of Method cannot be <code>null</code>,
+     * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
+     * <br>
+     * By <i>Default</i> the MethodSignatureBuilder SHOULD be pre-set as
+     * {@link MethodSignatureBuilder#setAbstract(true)}, {@link MethodSignatureBuilder#setFinal(false)} and
+     * {@link MethodSignatureBuilder#setAccessModifier(PUBLIC)}
+     *
+     * @param name Name of Method
+     * @return <code>new</code> instance of Method Signature Builder.
+     */
     public MethodSignatureBuilder addMethod(final String name);
 
+    /**
+     * Returns the <code>new</code> <i>immutable</i> instance of Generated
+     * Type.
+     *
+     * @return the <code>new</code> <i>immutable</i> instance of Generated
+     * Type.
+     */
     public GeneratedType toInstance();
 }
index 572d15faf4bee363e2c276cfd59b4788d5ce860e..70ea9bbb00491e074bef6b4216577006dc444e9c 100644 (file)
@@ -11,15 +11,58 @@ package org.opendaylight.controller.sal.binding.model.api.type.builder;
 import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
 import org.opendaylight.controller.sal.binding.model.api.Type;
 
-public interface MethodSignatureBuilder {
-    
-    public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
-    
-    public void addReturnType(final Type returnType);
+/**
+ * Method Signature Builder serves solely for building Method Signature and
+ * returning the <code>new</code> instance of Method Signature.
+ * <br>
+ * By definition of {@link MethodSignature} the Method in java MUST contain
+ * Name, Return Type and Access Modifier. By default the Access Modifier can
+ * be set to public. The Method Signature builder does not contain method for
+ * addName due to enforce reason that MethodSignatureBuilder SHOULD be
+ * instantiated only once with defined method name.
+ * <br>
+ * The methods as {@link #addAnnotation(String, String)} and {@link #setComment(String)}
+ * can be used as optional because not all methods MUST contain annotation or
+ * comment definitions.
+ *
+ *
+ * @see MethodSignature
+ */
+public interface MethodSignatureBuilder extends TypeMemberBuilder {
 
-    public void addParameter(final Type type, final String name);
+    /**
+     * Sets the flag for declaration of method as abstract or non abstract. If the flag <code>isAbstract == true</code>
+     * The instantiated Method Signature MUST have return value for {@link org.opendaylight.controller.sal.binding
+     * .model.api.MethodSignature#isAbstract()} also equals to <code>true</code>.
+     *
+     * @param isAbstract is abstract flag
+     */
+    public void setAbstract(boolean isAbstract);
 
-    public void addComment(final String comment);
+    /**
+     * Adds Parameter into the List of method parameters. Neither the Name or
+     * Type of parameter can be <code>null</code>.
+     *
+     * <br>
+     * In case that any of parameters are defined as <code>null</code> the
+     * method SHOULD throw an {@link IllegalArgumentException}
+     *
+     * @param type Parameter Type
+     * @param name Parameter Name
+     */
+    public void addParameter(final Type type, final String name);
 
+    /**
+     * Returns <code>new</code> <i>immutable</i> instance of Method Signature.
+     * <br>
+     * The <code>definingType</code> param cannot be <code>null</code>. The
+     * every method in Java MUST be declared and defined inside the scope of
+     * <code>class</code> or <code>interface</code> definition. In case that
+     * defining Type will be passed as <code>null</code> reference the method
+     * SHOULD thrown {@link IllegalArgumentException}.
+     *
+     * @param definingType Defining Type of Method Signature
+     * @return <code>new</code> <i>immutable</i> instance of Method Signature.
+     */
     public MethodSignature toInstance(final Type definingType);
 }
diff --git a/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/TypeMemberBuilder.java b/opendaylight/sal/yang-prototype/code-generator/binding-model-api/src/main/java/org/opendaylight/controller/sal/binding/model/api/type/builder/TypeMemberBuilder.java
new file mode 100644 (file)
index 0000000..de19360
--- /dev/null
@@ -0,0 +1,69 @@
+package org.opendaylight.controller.sal.binding.model.api.type.builder;
+
+import org.opendaylight.controller.sal.binding.model.api.AccessModifier;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+
+/**
+ *
+ */
+public interface TypeMemberBuilder {
+
+    /**
+     * The method creates new AnnotationTypeBuilder containing specified
+     * package name an annotation name.
+     * <br>
+     * Neither the package name or annotation name can contain
+     * <code>null</code> references. In case that
+     * any of parameters contains <code>null</code> the method SHOULD thrown
+     * {@link IllegalArgumentException}
+     *
+     * @param packageName Package Name of Annotation Type
+     * @param name Name of Annotation Type
+     * @return <code>new</code> instance of Annotation Type Builder.
+     */
+    public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
+
+    /**
+     * Returns the name of property.
+     *
+     * @return the name of property.
+     */
+    public String getName();
+
+    /**
+     * Adds return Type into Builder definition for Generated Property.
+     * <br>
+     * The return Type MUST NOT be <code>null</code>,
+     * otherwise the method SHOULD throw {@link IllegalArgumentException}
+     *
+     * @param returnType Return Type of property.
+     */
+    public void setReturnType(final Type returnType);
+
+    /**
+     * Sets the access modifier of property.
+     *
+     * @param modifier Access Modifier value.
+     */
+    public void setAccessModifier(final AccessModifier modifier);
+
+    /**
+     * Adds String definition of comment into Method Signature definition.
+     * <br>
+     * The comment String MUST NOT contain anny comment specific chars (i.e.
+     * "/**" or "//") just plain String text description.
+     *
+     * @param comment Comment String.
+     */
+    public void setComment(final String comment);
+
+    /**
+     * Sets the flag final for method signature. If this is set the method will be prohibited from overriding.
+     * <br>
+     * This setting is irrelevant for methods designated to be defined in interface definitions because interface
+     * can't have final method.
+     *
+     * @param isFinal Is Final
+     */
+    public void setFinal(final boolean isFinal);
+}
index a9e2b3b0feb8c09340901df26adfb6efc03a8dba..f520bf917a814ac362fc30e62f36b6616691fd5d 100644 (file)
@@ -102,8 +102,7 @@ public final class ChoiceBuilder implements DataSchemaNodeBuilder, AugmentationT
 
     public void addChildNode(DataSchemaNodeBuilder childNode) {
         if (!(childNode instanceof ChoiceCaseBuilder)) {
-            ChoiceCaseBuilder caseBuilder = new ChoiceCaseBuilder(
-                    childNode.getQName(), childNode.getLine());
+            ChoiceCaseBuilder caseBuilder = new ChoiceCaseBuilder(childNode.getQName(), childNode.getLine());
             caseBuilder.addChildNode(childNode);
             cases.add(caseBuilder);
         } else {
@@ -203,7 +202,6 @@ public final class ChoiceBuilder implements DataSchemaNodeBuilder, AugmentationT
         this.defaultCase = defaultCase;
     }
 
-
     private final class ChoiceNodeImpl implements ChoiceNode {
         private final QName qname;
         private SchemaPath path;
@@ -297,8 +295,7 @@ public final class ChoiceBuilder implements DataSchemaNodeBuilder, AugmentationT
             return augmentations;
         }
 
-        private void setAvailableAugmentations(
-                Set<AugmentationSchema> availableAugmentations) {
+        private void setAvailableAugmentations(Set<AugmentationSchema> availableAugmentations) {
             if (availableAugmentations != null) {
                 this.augmentations = availableAugmentations;
             }
@@ -309,8 +306,7 @@ public final class ChoiceBuilder implements DataSchemaNodeBuilder, AugmentationT
             return unknownNodes;
         }
 
-        private void setUnknownSchemaNodes(
-                List<UnknownSchemaNode> unknownSchemaNodes) {
+        private void setUnknownSchemaNodes(List<UnknownSchemaNode> unknownSchemaNodes) {
             if (unknownSchemaNodes != null) {
                 this.unknownNodes = unknownSchemaNodes;
             }
@@ -327,6 +323,7 @@ public final class ChoiceBuilder implements DataSchemaNodeBuilder, AugmentationT
             }
         }
 
+        @Override
         public String getDefaultCase() {
             return defaultCase;
         }
@@ -375,8 +372,7 @@ public final class ChoiceBuilder implements DataSchemaNodeBuilder, AugmentationT
 
         @Override
         public String toString() {
-            StringBuilder sb = new StringBuilder(
-                    ChoiceNodeImpl.class.getSimpleName());
+            StringBuilder sb = new StringBuilder(ChoiceNodeImpl.class.getSimpleName());
             sb.append("[");
             sb.append("qname=" + qname);
             sb.append("]");
index 6cbcec1054a1b58256fe4cec1e6731cce7ef0d41..855d0264ae911f875951f04a3a6b0ae94a55b529 100644 (file)
@@ -26,8 +26,7 @@ import org.opendaylight.controller.yang.parser.builder.api.SchemaNodeBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.TypeDefinitionAwareBuilder;
 import org.opendaylight.controller.yang.parser.builder.api.TypeDefinitionBuilder;
 
-public final class RpcDefinitionBuilder implements SchemaNodeBuilder,
-        TypeDefinitionAwareBuilder {
+public final class RpcDefinitionBuilder implements SchemaNodeBuilder, TypeDefinitionAwareBuilder {
     private boolean isBuilt;
     private final RpcDefinitionImpl instance;
     private final int line;
@@ -48,8 +47,8 @@ public final class RpcDefinitionBuilder implements SchemaNodeBuilder,
     @Override
     public RpcDefinition build() {
         if (!isBuilt) {
-            final ContainerSchemaNode input = inputBuilder.build();
-            final ContainerSchemaNode output = outputBuilder.build();
+            final ContainerSchemaNode input = inputBuilder == null ? null : inputBuilder.build();
+            final ContainerSchemaNode output = outputBuilder == null ? null : outputBuilder.build();
             instance.setInput(input);
             instance.setOutput(output);
 
@@ -314,8 +313,7 @@ public final class RpcDefinitionBuilder implements SchemaNodeBuilder,
 
         @Override
         public String toString() {
-            StringBuilder sb = new StringBuilder(
-                    RpcDefinitionImpl.class.getSimpleName() + "[");
+            StringBuilder sb = new StringBuilder(RpcDefinitionImpl.class.getSimpleName() + "[");
             sb.append("qname=" + qname);
             sb.append(", path=" + path);
             sb.append(", input=" + input);
index 94437170f4be3c8ef91ae774debd26cb1d4f8963..6814322bde1721ef7b7ba3f258279bf2882bc601 100644 (file)
@@ -84,8 +84,7 @@ import com.google.common.collect.Sets;
 
 public final class YangParserImpl implements YangModelParser {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(YangParserImpl.class);
+    private static final Logger logger = LoggerFactory.getLogger(YangParserImpl.class);
 
     @Override
     public Map<File, Module> parseYangModelsMapped(List<File> yangFiles) {
@@ -96,27 +95,22 @@ public final class YangParserImpl implements YangModelParser {
                 try {
                     inputStreams.put(new FileInputStream(yangFile), yangFile);
                 } catch (FileNotFoundException e) {
-                    logger.warn("Exception while reading yang file: "
-                            + yangFile.getName(), e);
+                    logger.warn("Exception while reading yang file: " + yangFile.getName(), e);
                 }
             }
 
-            Map<ModuleBuilder, InputStream> builderToStreamMap = Maps
-                    .newHashMap();
+            Map<ModuleBuilder, InputStream> builderToStreamMap = Maps.newHashMap();
 
             final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(
-                    Lists.newArrayList(inputStreams.keySet()),
-                    builderToStreamMap);
+                    Lists.newArrayList(inputStreams.keySet()), builderToStreamMap);
             // return new LinkedHashSet<Module>(build(modules).values());
 
             Map<File, Module> retVal = Maps.newLinkedHashMap();
             Map<ModuleBuilder, Module> builderToModuleMap = build(modules);
 
-            for (Entry<ModuleBuilder, Module> builderToModule : builderToModuleMap
-                    .entrySet()) {
-                retVal.put(inputStreams.get(builderToStreamMap
-                        .get(builderToModule.getKey())), builderToModule
-                        .getValue());
+            for (Entry<ModuleBuilder, Module> builderToModule : builderToModuleMap.entrySet()) {
+                retVal.put(inputStreams.get(builderToStreamMap.get(builderToModule.getKey())),
+                        builderToModule.getValue());
             }
 
             return retVal;
@@ -130,26 +124,21 @@ public final class YangParserImpl implements YangModelParser {
     }
 
     @Override
-    public Set<Module> parseYangModelsFromStreams(
-            final List<InputStream> yangModelStreams) {
-        return Sets.newHashSet(parseYangModelsFromStreamsMapped(
-                yangModelStreams).values());
+    public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
+        return Sets.newHashSet(parseYangModelsFromStreamsMapped(yangModelStreams).values());
     }
 
     @Override
-    public Map<InputStream, Module> parseYangModelsFromStreamsMapped(
-            final List<InputStream> yangModelStreams) {
+    public Map<InputStream, Module> parseYangModelsFromStreamsMapped(final List<InputStream> yangModelStreams) {
         Map<ModuleBuilder, InputStream> builderToStreamMap = Maps.newHashMap();
 
-        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(
-                yangModelStreams, builderToStreamMap);
+        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangModelStreams,
+                builderToStreamMap);
         Map<InputStream, Module> retVal = Maps.newLinkedHashMap();
         Map<ModuleBuilder, Module> builderToModuleMap = build(modules);
 
-        for (Entry<ModuleBuilder, Module> builderToModule : builderToModuleMap
-                .entrySet()) {
-            retVal.put(builderToStreamMap.get(builderToModule.getKey()),
-                    builderToModule.getValue());
+        for (Entry<ModuleBuilder, Module> builderToModule : builderToModuleMap.entrySet()) {
+            retVal.put(builderToStreamMap.get(builderToModule.getKey()), builderToModule.getValue());
         }
         return retVal;
     }
@@ -182,12 +171,10 @@ public final class YangParserImpl implements YangModelParser {
         return builders;
     }
 
-    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
-            final List<InputStream> yangFileStreams,
+    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(final List<InputStream> yangFileStreams,
             Map<ModuleBuilder, InputStream> streamToBuilderMap) {
 
-        final ModuleBuilder[] builders = parseModuleBuilders(yangFileStreams,
-                streamToBuilderMap);
+        final ModuleBuilder[] builders = parseModuleBuilders(yangFileStreams, streamToBuilderMap);
 
         // Linked Hash Map MUST be used because Linked Hash Map preserves ORDER
         // of items stored in map.
@@ -202,8 +189,7 @@ public final class YangParserImpl implements YangModelParser {
             if (builderRevision == null) {
                 builderRevision = new Date(0L);
             }
-            TreeMap<Date, ModuleBuilder> builderByRevision = modules
-                    .get(builderName);
+            TreeMap<Date, ModuleBuilder> builderByRevision = modules.get(builderName);
             if (builderByRevision == null) {
                 builderByRevision = new TreeMap<Date, ModuleBuilder>();
             }
@@ -236,13 +222,10 @@ public final class YangParserImpl implements YangModelParser {
         return result;
     }
 
-    private Map<ModuleBuilder, Module> build(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules) {
+    private Map<ModuleBuilder, Module> build(final Map<String, TreeMap<Date, ModuleBuilder>> modules) {
         // fix unresolved nodes
-        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules
-                .entrySet()) {
-            for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue()
-                    .entrySet()) {
+        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+            for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
                 final ModuleBuilder moduleBuilder = childEntry.getValue();
                 fixUnresolvedNodes(modules, moduleBuilder);
             }
@@ -254,11 +237,9 @@ public final class YangParserImpl implements YangModelParser {
         // order!
         // http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html
         final Map<ModuleBuilder, Module> result = new LinkedHashMap<ModuleBuilder, Module>();
-        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules
-                .entrySet()) {
+        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
             final Map<Date, Module> modulesByRevision = new HashMap<Date, Module>();
-            for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue()
-                    .entrySet()) {
+            for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
                 final ModuleBuilder moduleBuilder = childEntry.getValue();
                 final Module module = moduleBuilder.build();
                 modulesByRevision.put(childEntry.getKey(), module);
@@ -268,9 +249,7 @@ public final class YangParserImpl implements YangModelParser {
         return result;
     }
 
-    private void fixUnresolvedNodes(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder builder) {
+    private void fixUnresolvedNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder builder) {
         resolveDirtyNodes(modules, builder);
         resolveIdentities(modules, builder);
         resolveUsesRefines(modules, builder);
@@ -286,26 +265,19 @@ public final class YangParserImpl implements YangModelParser {
      * @param module
      *            current module
      */
-    private void resolveDirtyNodes(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
-        final Map<List<String>, TypeAwareBuilder> dirtyNodes = module
-                .getDirtyNodes();
+    private void resolveDirtyNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+        final Map<List<String>, TypeAwareBuilder> dirtyNodes = module.getDirtyNodes();
         if (!dirtyNodes.isEmpty()) {
-            for (Map.Entry<List<String>, TypeAwareBuilder> entry : dirtyNodes
-                    .entrySet()) {
+            for (Map.Entry<List<String>, TypeAwareBuilder> entry : dirtyNodes.entrySet()) {
                 final TypeAwareBuilder nodeToResolve = entry.getValue();
 
                 if (nodeToResolve instanceof UnionTypeBuilder) {
                     // special handling for union types
-                    resolveTypeUnion((UnionTypeBuilder) nodeToResolve, modules,
-                            module);
+                    resolveTypeUnion((UnionTypeBuilder) nodeToResolve, modules, module);
                 } else if (nodeToResolve.getTypedef() instanceof IdentityrefTypeBuilder) {
                     // special handling for identityref types
-                    IdentityrefTypeBuilder idref = (IdentityrefTypeBuilder) nodeToResolve
-                            .getTypedef();
-                    nodeToResolve.setType(new IdentityrefType(findFullQName(
-                            modules, module, idref), idref.getPath()));
+                    IdentityrefTypeBuilder idref = (IdentityrefTypeBuilder) nodeToResolve.getTypedef();
+                    nodeToResolve.setType(new IdentityrefType(findFullQName(modules, module, idref), idref.getPath()));
                 } else {
                     resolveType(nodeToResolve, modules, module);
                 }
@@ -314,46 +286,45 @@ public final class YangParserImpl implements YangModelParser {
     }
 
     private void resolveType(final TypeAwareBuilder nodeToResolve,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder builder) {
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder builder) {
         TypeDefinitionBuilder resolvedType = null;
         final int line = nodeToResolve.getLine();
-        final TypeDefinition<?> typedefType = nodeToResolve.getType();
-        final QName unknownTypeQName = typedefType.getBaseType().getQName();
-        final ModuleBuilder dependentModule = findDependentModule(modules,
-                builder, unknownTypeQName.getPrefix(), line);
-
-        final TypeDefinitionBuilder targetTypeBuilder = findTypeDefinitionBuilder(
-                nodeToResolve.getPath(), dependentModule,
-                unknownTypeQName.getLocalName(), builder.getName(), line);
-
-        if (typedefType instanceof ExtendedType) {
-            final ExtendedType extType = (ExtendedType) typedefType;
-            final TypeDefinitionBuilder newType = extendedTypeWithNewBaseType(
-                    nodeToResolve, targetTypeBuilder, extType, modules, builder);
+        final TypeDefinition<?> nodeToResolveType = nodeToResolve.getType();
+        final QName unknownTypeQName = nodeToResolveType.getBaseType().getQName();
+        final ModuleBuilder dependentModule = findDependentModule(modules, builder, unknownTypeQName.getPrefix(), line);
+
+        final TypeDefinitionBuilder targetTypeBuilder = findTypeDefinitionBuilder(nodeToResolve.getPath(),
+                dependentModule, unknownTypeQName.getLocalName(), builder.getName(), line);
+
+        if (nodeToResolveType instanceof ExtendedType) {
+            final ExtendedType extType = (ExtendedType) nodeToResolveType;
+            final TypeDefinitionBuilder newType = extendedTypeWithNewBaseType(nodeToResolve, targetTypeBuilder,
+                    extType, modules, builder);
             resolvedType = newType;
         } else {
             resolvedType = targetTypeBuilder;
         }
+
+        // validate constraints
+        final TypeConstraints constraints = findConstraints(nodeToResolve, new TypeConstraints(builder.getName(),
+                nodeToResolve.getLine()), modules, builder);
+        constraints.validateConstraints();
+
         nodeToResolve.setTypedef(resolvedType);
     }
 
     private void resolveTypeUnion(final UnionTypeBuilder union,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder builder) {
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder builder) {
 
         final List<TypeDefinition<?>> unionTypes = union.getTypes();
         final List<TypeDefinition<?>> toRemove = new ArrayList<TypeDefinition<?>>();
         for (TypeDefinition<?> unionType : unionTypes) {
             if (unionType instanceof UnknownType) {
                 final UnknownType ut = (UnknownType) unionType;
-                final ModuleBuilder dependentModule = findDependentModule(
-                        modules, builder, ut.getQName().getPrefix(),
-                        union.getLine());
-                final TypeDefinitionBuilder resolvedType = findTypeDefinitionBuilder(
-                        union.getPath(), dependentModule, ut.getQName()
-                                .getLocalName(), builder.getName(),
+                final ModuleBuilder dependentModule = findDependentModule(modules, builder, ut.getQName().getPrefix(),
                         union.getLine());
+                final TypeDefinitionBuilder resolvedType = findTypeDefinitionBuilder(union.getPath(), dependentModule,
+                        ut.getQName().getLocalName(), builder.getName(), union.getLine());
                 union.setTypedef(resolvedType);
                 toRemove.add(ut);
             } else if (unionType instanceof ExtendedType) {
@@ -361,17 +332,13 @@ public final class YangParserImpl implements YangModelParser {
                 TypeDefinition<?> extTypeBase = extType.getBaseType();
                 if (extTypeBase instanceof UnknownType) {
                     final UnknownType ut = (UnknownType) extTypeBase;
-                    final ModuleBuilder dependentModule = findDependentModule(
-                            modules, builder, ut.getQName().getPrefix(),
-                            union.getLine());
-                    final TypeDefinitionBuilder targetTypeBuilder = findTypeDefinitionBuilder(
-                            union.getPath(), dependentModule, ut.getQName()
-                                    .getLocalName(), builder.getName(),
-                            union.getLine());
-
-                    final TypeDefinitionBuilder newType = extendedTypeWithNewBaseType(
-                            targetTypeBuilder, targetTypeBuilder, extType,
-                            modules, builder);
+                    final ModuleBuilder dependentModule = findDependentModule(modules, builder, ut.getQName()
+                            .getPrefix(), union.getLine());
+                    final TypeDefinitionBuilder targetTypeBuilder = findTypeDefinitionBuilder(union.getPath(),
+                            dependentModule, ut.getQName().getLocalName(), builder.getName(), union.getLine());
+
+                    final TypeDefinitionBuilder newType = extendedTypeWithNewBaseType(targetTypeBuilder,
+                            targetTypeBuilder, extType, modules, builder);
 
                     union.setTypedef(newType);
                     toRemove.add(extType);
@@ -381,16 +348,13 @@ public final class YangParserImpl implements YangModelParser {
         unionTypes.removeAll(toRemove);
     }
 
-    private TypeDefinitionBuilder extendedTypeWithNewBaseType(
-            final TypeAwareBuilder nodeToResolve,
-            final TypeDefinitionBuilder newBaseType,
-            final ExtendedType oldExtendedType,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder builder) {
-        final TypeConstraints constraints = findConstraints(nodeToResolve,
-                new TypeConstraints(), modules, builder);
-        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(
-                oldExtendedType.getQName(), nodeToResolve.getLine());
+    private TypeDefinitionBuilder extendedTypeWithNewBaseType(final TypeAwareBuilder nodeToResolve,
+            final TypeDefinitionBuilder newBaseType, final ExtendedType oldExtendedType,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder builder) {
+        final TypeConstraints constraints = findConstraints(nodeToResolve, new TypeConstraints(builder.getName(),
+                nodeToResolve.getLine()), modules, builder);
+        final TypeDefinitionBuilderImpl newType = new TypeDefinitionBuilderImpl(oldExtendedType.getQName(),
+                nodeToResolve.getLine());
         newType.setTypedef(newBaseType);
         newType.setPath(oldExtendedType.getPath());
         newType.setDescription(oldExtendedType.getDescription());
@@ -406,11 +370,8 @@ public final class YangParserImpl implements YangModelParser {
         return newType;
     }
 
-    private TypeConstraints findConstraints(
-            final TypeAwareBuilder nodeToResolve,
-            final TypeConstraints constraints,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder builder) {
+    private TypeConstraints findConstraints(final TypeAwareBuilder nodeToResolve, final TypeConstraints constraints,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder builder) {
 
         // union type cannot be restricted
         if (nodeToResolve instanceof UnionTypeBuilder) {
@@ -427,19 +388,14 @@ public final class YangParserImpl implements YangModelParser {
 
         TypeDefinition<?> type = nodeToResolve.getType();
         if (type == null) {
-            return findConstraints(nodeToResolve.getTypedef(), constraints,
-                    modules, builder);
+            return findConstraints(nodeToResolve.getTypedef(), constraints, modules, builder);
         } else {
             if (type instanceof UnknownType) {
-                ModuleBuilder dependentModule = findDependentModule(modules,
-                        builder, type.getQName().getPrefix(),
+                ModuleBuilder dependentModule = findDependentModule(modules, builder, type.getQName().getPrefix(),
                         nodeToResolve.getLine());
-                TypeDefinitionBuilder tdb = findTypeDefinitionBuilder(
-                        nodeToResolve.getPath(), dependentModule, type
-                                .getQName().getLocalName(), builder.getName(),
-                        nodeToResolve.getLine());
-                return findConstraints(tdb, constraints, modules,
-                        dependentModule);
+                TypeDefinitionBuilder tdb = findTypeDefinitionBuilder(nodeToResolve.getPath(), dependentModule, type
+                        .getQName().getLocalName(), builder.getName(), nodeToResolve.getLine());
+                return findConstraints(tdb, constraints, modules, dependentModule);
             } else if (type instanceof ExtendedType) {
                 ExtendedType extType = (ExtendedType) type;
                 constraints.addFractionDigits(extType.getFractionDigits());
@@ -449,15 +405,11 @@ public final class YangParserImpl implements YangModelParser {
 
                 TypeDefinition<?> base = extType.getBaseType();
                 if (base instanceof UnknownType) {
-                    ModuleBuilder dependentModule = findDependentModule(
-                            modules, builder, base.getQName().getPrefix(),
+                    ModuleBuilder dependentModule = findDependentModule(modules, builder, base.getQName().getPrefix(),
                             nodeToResolve.getLine());
-                    TypeDefinitionBuilder tdb = findTypeDefinitionBuilder(
-                            nodeToResolve.getPath(), dependentModule, base
-                                    .getQName().getLocalName(),
-                            builder.getName(), nodeToResolve.getLine());
-                    return findConstraints(tdb, constraints, modules,
-                            dependentModule);
+                    TypeDefinitionBuilder tdb = findTypeDefinitionBuilder(nodeToResolve.getPath(), dependentModule,
+                            base.getQName().getLocalName(), builder.getName(), nodeToResolve.getLine());
+                    return findConstraints(tdb, constraints, modules, dependentModule);
                 } else {
                     // it has to be base yang type
                     mergeConstraints(type, constraints);
@@ -486,15 +438,12 @@ public final class YangParserImpl implements YangModelParser {
      *            current line in yang model
      * @return
      */
-    private TypeDefinitionBuilder findTypeDefinitionBuilder(
-            SchemaPath dirtyNodeSchemaPath,
-            final ModuleBuilder dependentModule, final String typeName,
-            final String currentModuleName, final int line) {
+    private TypeDefinitionBuilder findTypeDefinitionBuilder(SchemaPath dirtyNodeSchemaPath,
+            final ModuleBuilder dependentModule, final String typeName, final String currentModuleName, final int line) {
         final List<QName> path = dirtyNodeSchemaPath.getPath();
         TypeDefinitionBuilder result = null;
 
-        Set<TypeDefinitionBuilder> typedefs = dependentModule
-                .getModuleTypedefs();
+        Set<TypeDefinitionBuilder> typedefs = dependentModule.getModuleTypedefs();
         result = findTdb(typedefs, typeName);
 
         if (result == null) {
@@ -508,11 +457,9 @@ public final class YangParserImpl implements YangModelParser {
                 currentNode = dependentModule.getModuleNode(currentPath);
 
                 if (currentNode instanceof RpcDefinitionBuilder) {
-                    typedefs = ((RpcDefinitionBuilder) currentNode)
-                            .getTypeDefinitions();
+                    typedefs = ((RpcDefinitionBuilder) currentNode).getTypeDefinitions();
                 } else if (currentNode instanceof DataNodeContainerBuilder) {
-                    typedefs = ((DataNodeContainerBuilder) currentNode)
-                            .getTypeDefinitions();
+                    typedefs = ((DataNodeContainerBuilder) currentNode).getTypeDefinitions();
                 } else {
                     typedefs = Collections.emptySet();
                 }
@@ -527,12 +474,10 @@ public final class YangParserImpl implements YangModelParser {
         if (result != null) {
             return result;
         }
-        throw new YangParseException(currentModuleName, line,
-                "Referenced type '" + typeName + "' not found.");
+        throw new YangParseException(currentModuleName, line, "Referenced type '" + typeName + "' not found.");
     }
 
-    private TypeDefinitionBuilder findTdb(Set<TypeDefinitionBuilder> types,
-            String name) {
+    private TypeDefinitionBuilder findTdb(Set<TypeDefinitionBuilder> types, String name) {
         for (TypeDefinitionBuilder td : types) {
             if (td.getQName().getLocalName().equals(name)) {
                 return td;
@@ -547,26 +492,18 @@ public final class YangParserImpl implements YangModelParser {
      * @param referencedType
      * @param constraints
      */
-    private void mergeConstraints(final TypeDefinition<?> referencedType,
-            final TypeConstraints constraints) {
+    private void mergeConstraints(final TypeDefinition<?> referencedType, final TypeConstraints constraints) {
 
         if (referencedType instanceof DecimalTypeDefinition) {
-            constraints.addRanges(((DecimalTypeDefinition) referencedType)
-                    .getRangeStatements());
-            constraints
-                    .addFractionDigits(((DecimalTypeDefinition) referencedType)
-                            .getFractionDigits());
+            constraints.addRanges(((DecimalTypeDefinition) referencedType).getRangeStatements());
+            constraints.addFractionDigits(((DecimalTypeDefinition) referencedType).getFractionDigits());
         } else if (referencedType instanceof IntegerTypeDefinition) {
-            constraints.addRanges(((IntegerTypeDefinition) referencedType)
-                    .getRangeStatements());
+            constraints.addRanges(((IntegerTypeDefinition) referencedType).getRangeStatements());
         } else if (referencedType instanceof StringTypeDefinition) {
-            constraints.addPatterns(((StringTypeDefinition) referencedType)
-                    .getPatterns());
-            constraints.addLengths(((StringTypeDefinition) referencedType)
-                    .getLengthStatements());
+            constraints.addPatterns(((StringTypeDefinition) referencedType).getPatterns());
+            constraints.addLengths(((StringTypeDefinition) referencedType).getLengthStatements());
         } else if (referencedType instanceof BinaryTypeDefinition) {
-            constraints.addLengths(((BinaryTypeDefinition) referencedType)
-                    .getLengthConstraints());
+            constraints.addLengths(((BinaryTypeDefinition) referencedType).getLengthConstraints());
         }
     }
 
@@ -577,14 +514,11 @@ public final class YangParserImpl implements YangModelParser {
      * @param modules
      *            all available modules
      */
-    private void resolveAugments(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules) {
+    private void resolveAugments(final Map<String, TreeMap<Date, ModuleBuilder>> modules) {
         final List<ModuleBuilder> allModulesList = new ArrayList<ModuleBuilder>();
         final Set<ModuleBuilder> allModulesSet = new HashSet<ModuleBuilder>();
-        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules
-                .entrySet()) {
-            for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue()
-                    .entrySet()) {
+        for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
+            for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
                 allModulesList.add(inner.getValue());
                 allModulesSet.add(inner.getValue());
             }
@@ -595,19 +529,15 @@ public final class YangParserImpl implements YangModelParser {
             // try to resolve augments in module
             resolveAugment(modules, module);
             // while all augments are not resolved
-            final Iterator<ModuleBuilder> allModulesIterator = allModulesSet
-                    .iterator();
-            while (!(module.getAugmentsResolved() == module.getAugments()
-                    .size())) {
+            final Iterator<ModuleBuilder> allModulesIterator = allModulesSet.iterator();
+            while (!(module.getAugmentsResolved() == module.getAugments().size())) {
                 ModuleBuilder nextModule = null;
                 // try resolve other module augments
                 try {
                     nextModule = allModulesIterator.next();
                     resolveAugment(modules, nextModule);
                 } catch (NoSuchElementException e) {
-                    throw new YangParseException(
-                            "Failed to resolve augments in module '"
-                                    + module.getName() + "'.", e);
+                    throw new YangParseException("Failed to resolve augments in module '" + module.getName() + "'.", e);
                 }
                 // then try to resolve first module again
                 resolveAugment(modules, module);
@@ -622,16 +552,12 @@ public final class YangParserImpl implements YangModelParser {
      * @param module
      *            current module
      */
-    private void resolveAugment(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
+    private void resolveAugment(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
         if (module.getAugmentsResolved() < module.getAugments().size()) {
-            for (AugmentationSchemaBuilder augmentBuilder : module
-                    .getAugments()) {
+            for (AugmentationSchemaBuilder augmentBuilder : module.getAugments()) {
 
                 if (!augmentBuilder.isResolved()) {
-                    final SchemaPath augmentTargetSchemaPath = augmentBuilder
-                            .getTargetPath();
+                    final SchemaPath augmentTargetSchemaPath = augmentBuilder.getTargetPath();
                     final List<QName> path = augmentTargetSchemaPath.getPath();
 
                     final QName qname = path.get(0);
@@ -641,13 +567,11 @@ public final class YangParserImpl implements YangModelParser {
                     }
 
                     DataSchemaNodeBuilder currentParent = null;
-                    final ModuleBuilder dependentModule = findDependentModule(
-                            modules, module, prefix, augmentBuilder.getLine());
-                    for (DataSchemaNodeBuilder child : dependentModule
-                            .getChildNodes()) {
+                    final ModuleBuilder dependentModule = findDependentModule(modules, module, prefix,
+                            augmentBuilder.getLine());
+                    for (DataSchemaNodeBuilder child : dependentModule.getChildNodes()) {
                         final QName childQName = child.getQName();
-                        if (childQName.getLocalName().equals(
-                                qname.getLocalName())) {
+                        if (childQName.getLocalName().equals(qname.getLocalName())) {
                             currentParent = child;
                             break;
                         }
@@ -660,11 +584,9 @@ public final class YangParserImpl implements YangModelParser {
                     for (int i = 1; i < path.size(); i++) {
                         final QName currentQName = path.get(i);
                         DataSchemaNodeBuilder newParent = null;
-                        for (DataSchemaNodeBuilder child : ((DataNodeContainerBuilder) currentParent)
-                                .getChildNodes()) {
+                        for (DataSchemaNodeBuilder child : ((DataNodeContainerBuilder) currentParent).getChildNodes()) {
                             final QName childQName = child.getQName();
-                            if (childQName.getLocalName().equals(
-                                    currentQName.getLocalName())) {
+                            if (childQName.getLocalName().equals(currentQName.getLocalName())) {
                                 newParent = child;
                                 break;
                             }
@@ -677,23 +599,17 @@ public final class YangParserImpl implements YangModelParser {
                     }
 
                     final QName currentQName = currentParent.getQName();
-                    final QName lastAugmentPathElement = path
-                            .get(path.size() - 1);
-                    if (currentQName.getLocalName().equals(
-                            lastAugmentPathElement.getLocalName())) {
+                    final QName lastAugmentPathElement = path.get(path.size() - 1);
+                    if (currentQName.getLocalName().equals(lastAugmentPathElement.getLocalName())) {
 
                         if (currentParent instanceof ChoiceBuilder) {
-                            ParserUtils.fillAugmentTarget(augmentBuilder,
-                                    (ChoiceBuilder) currentParent);
+                            ParserUtils.fillAugmentTarget(augmentBuilder, (ChoiceBuilder) currentParent);
                         } else {
-                            ParserUtils.fillAugmentTarget(augmentBuilder,
-                                    (DataNodeContainerBuilder) currentParent);
+                            ParserUtils.fillAugmentTarget(augmentBuilder, (DataNodeContainerBuilder) currentParent);
                         }
-                        ((AugmentationTargetBuilder) currentParent)
-                                .addAugmentation(augmentBuilder);
+                        ((AugmentationTargetBuilder) currentParent).addAugmentation(augmentBuilder);
                         SchemaPath oldPath = currentParent.getPath();
-                        augmentBuilder.setTargetPath(new SchemaPath(oldPath
-                                .getPath(), oldPath.isAbsolute()));
+                        augmentBuilder.setTargetPath(new SchemaPath(oldPath.getPath(), oldPath.isAbsolute()));
                         augmentBuilder.setResolved(true);
                         module.augmentResolved();
                     }
@@ -712,11 +628,8 @@ public final class YangParserImpl implements YangModelParser {
      * @param module
      *            module being resolved
      */
-    private void resolveIdentities(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
-        final Set<IdentitySchemaNodeBuilder> identities = module
-                .getIdentities();
+    private void resolveIdentities(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+        final Set<IdentitySchemaNodeBuilder> identities = module.getIdentities();
         for (IdentitySchemaNodeBuilder identity : identities) {
             final String baseIdentityName = identity.getBaseIdentityName();
             if (baseIdentityName != null) {
@@ -730,14 +643,12 @@ public final class YangParserImpl implements YangModelParser {
                     baseIdentityPrefix = module.getPrefix();
                     baseIdentityLocalName = baseIdentityName;
                 }
-                final ModuleBuilder dependentModule = findDependentModule(
-                        modules, module, baseIdentityPrefix, identity.getLine());
+                final ModuleBuilder dependentModule = findDependentModule(modules, module, baseIdentityPrefix,
+                        identity.getLine());
 
-                final Set<IdentitySchemaNodeBuilder> dependentModuleIdentities = dependentModule
-                        .getIdentities();
+                final Set<IdentitySchemaNodeBuilder> dependentModuleIdentities = dependentModule.getIdentities();
                 for (IdentitySchemaNodeBuilder idBuilder : dependentModuleIdentities) {
-                    if (idBuilder.getQName().getLocalName()
-                            .equals(baseIdentityLocalName)) {
+                    if (idBuilder.getQName().getLocalName().equals(baseIdentityLocalName)) {
                         identity.setBaseIdentity(idBuilder);
                     }
                 }
@@ -754,13 +665,9 @@ public final class YangParserImpl implements YangModelParser {
      * @param module
      *            module being resolved
      */
-    private void resolveUsesRefines(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
-        final Map<List<String>, UsesNodeBuilder> moduleUses = module
-                .getUsesNodes();
-        for (Map.Entry<List<String>, UsesNodeBuilder> entry : moduleUses
-                .entrySet()) {
+    private void resolveUsesRefines(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
+        final Map<List<String>, UsesNodeBuilder> moduleUses = module.getUsesNodes();
+        for (Map.Entry<List<String>, UsesNodeBuilder> entry : moduleUses.entrySet()) {
             final UsesNodeBuilder usesNode = entry.getValue();
             final int line = usesNode.getLine();
 
@@ -768,8 +675,7 @@ public final class YangParserImpl implements YangModelParser {
             usesNode.setGroupingPath(targetGrouping.getPath());
 
             for (RefineHolder refine : usesNode.getRefines()) {
-                SchemaNodeBuilder refineTarget = getRefineNodeBuilderCopy(
-                        targetGrouping, refine, modules, module);
+                SchemaNodeBuilder refineTarget = getRefineNodeBuilderCopy(targetGrouping, refine, modules, module);
                 ParserUtils.checkRefine(refineTarget, refine);
                 ParserUtils.refineDefault(refineTarget, refine, line);
                 if (refineTarget instanceof LeafSchemaNodeBuilder) {
@@ -805,18 +711,16 @@ public final class YangParserImpl implements YangModelParser {
         }
     }
 
-    private GroupingBuilder getTargetGrouping(
-            final UsesNodeBuilder usesBuilder,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
+    private GroupingBuilder getTargetGrouping(final UsesNodeBuilder usesBuilder,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
         final int line = usesBuilder.getLine();
         String groupingString = usesBuilder.getGroupingName();
         String groupingPrefix;
         String groupingName;
 
-        if(groupingString.contains(":")) {
+        if (groupingString.contains(":")) {
             String[] splitted = groupingString.split(":");
-            if(splitted.length != 2 || groupingString.contains("/")) {
+            if (splitted.length != 2 || groupingString.contains("/")) {
                 throw new YangParseException(module.getName(), line, "Invalid name of target grouping");
             }
             groupingPrefix = splitted[0];
@@ -827,13 +731,12 @@ public final class YangParserImpl implements YangModelParser {
         }
 
         ModuleBuilder dependentModule = null;
-        if(groupingPrefix.equals(module.getPrefix())) {
+        if (groupingPrefix.equals(module.getPrefix())) {
             dependentModule = module;
         } else {
             dependentModule = findDependentModule(modules, module, groupingPrefix, line);
         }
 
-
         List<QName> path = usesBuilder.getPath().getPath();
         GroupingBuilder result = null;
         Set<GroupingBuilder> groupings = dependentModule.getModuleGroupings();
@@ -867,12 +770,10 @@ public final class YangParserImpl implements YangModelParser {
         if (result != null) {
             return result;
         }
-        throw new YangParseException(module.getName(), line,
-                "Referenced grouping '" + groupingName + "' not found.");
+        throw new YangParseException(module.getName(), line, "Referenced grouping '" + groupingName + "' not found.");
     }
 
-    private GroupingBuilder findGrouping(Set<GroupingBuilder> groupings,
-            String name) {
+    private GroupingBuilder findGrouping(Set<GroupingBuilder> groupings, String name) {
         for (GroupingBuilder grouping : groupings) {
             if (grouping.getQName().getLocalName().equals(name)) {
                 return grouping;
@@ -900,40 +801,29 @@ public final class YangParserImpl implements YangModelParser {
      * @return copy of node to be refined if it is present in grouping, null
      *         otherwise
      */
-    private SchemaNodeBuilder getRefineNodeBuilderCopy(
-            final GroupingBuilder targetGrouping, final RefineHolder refine,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
+    private SchemaNodeBuilder getRefineNodeBuilderCopy(final GroupingBuilder targetGrouping, final RefineHolder refine,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
         Builder result = null;
-        final Builder lookedUpBuilder = findRefineTargetBuilder(targetGrouping,
-                refine, modules, module);
+        final Builder lookedUpBuilder = findRefineTargetBuilder(targetGrouping, refine, modules, module);
         if (lookedUpBuilder instanceof LeafSchemaNodeBuilder) {
-            result = ParserUtils
-                    .copyLeafBuilder((LeafSchemaNodeBuilder) lookedUpBuilder);
+            result = ParserUtils.copyLeafBuilder((LeafSchemaNodeBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof ContainerSchemaNodeBuilder) {
-            result = ParserUtils
-                    .copyContainerBuilder((ContainerSchemaNodeBuilder) lookedUpBuilder);
+            result = ParserUtils.copyContainerBuilder((ContainerSchemaNodeBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof ListSchemaNodeBuilder) {
-            result = ParserUtils
-                    .copyListBuilder((ListSchemaNodeBuilder) lookedUpBuilder);
+            result = ParserUtils.copyListBuilder((ListSchemaNodeBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof LeafListSchemaNodeBuilder) {
-            result = ParserUtils
-                    .copyLeafListBuilder((LeafListSchemaNodeBuilder) lookedUpBuilder);
+            result = ParserUtils.copyLeafListBuilder((LeafListSchemaNodeBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof ChoiceBuilder) {
-            result = ParserUtils
-                    .copyChoiceBuilder((ChoiceBuilder) lookedUpBuilder);
+            result = ParserUtils.copyChoiceBuilder((ChoiceBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof AnyXmlBuilder) {
-            result = ParserUtils
-                    .copyAnyXmlBuilder((AnyXmlBuilder) lookedUpBuilder);
+            result = ParserUtils.copyAnyXmlBuilder((AnyXmlBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof GroupingBuilder) {
-            result = ParserUtils
-                    .copyGroupingBuilder((GroupingBuilder) lookedUpBuilder);
+            result = ParserUtils.copyGroupingBuilder((GroupingBuilder) lookedUpBuilder);
         } else if (lookedUpBuilder instanceof TypeDefinitionBuilder) {
-            result = ParserUtils
-                    .copyTypedefBuilder((TypeDefinitionBuilderImpl) lookedUpBuilder);
+            result = ParserUtils.copyTypedefBuilder((TypeDefinitionBuilderImpl) lookedUpBuilder);
         } else {
-            throw new YangParseException(module.getName(), refine.getLine(),
-                    "Target '" + refine.getName() + "' can not be refined");
+            throw new YangParseException(module.getName(), refine.getLine(), "Target '" + refine.getName()
+                    + "' can not be refined");
         }
         return (SchemaNodeBuilder) result;
     }
@@ -952,10 +842,8 @@ public final class YangParserImpl implements YangModelParser {
      * @return Builder object of refine node if it is present in grouping, null
      *         otherwise
      */
-    private Builder findRefineTargetBuilder(final GroupingBuilder builder,
-            final RefineHolder refine,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
+    private Builder findRefineTargetBuilder(final GroupingBuilder builder, final RefineHolder refine,
+            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
         final String refineNodeName = refine.getName();
         Builder result = builder.getChildNode(refineNodeName);
         if (result == null) {
@@ -979,49 +867,38 @@ public final class YangParserImpl implements YangModelParser {
         return result;
     }
 
-    private QName findFullQName(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module, final IdentityrefTypeBuilder idref) {
+    private QName findFullQName(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module,
+            final IdentityrefTypeBuilder idref) {
         QName result = null;
         String baseString = idref.getBaseString();
         if (baseString.contains(":")) {
             String[] splittedBase = baseString.split(":");
             if (splittedBase.length > 2) {
-                throw new YangParseException(module.getName(), idref.getLine(),
-                        "Failed to parse identityref base: " + baseString);
+                throw new YangParseException(module.getName(), idref.getLine(), "Failed to parse identityref base: "
+                        + baseString);
             }
             String prefix = splittedBase[0];
             String name = splittedBase[1];
-            ModuleBuilder dependentModule = findDependentModule(modules,
-                    module, prefix, idref.getLine());
-            result = new QName(dependentModule.getNamespace(),
-                    dependentModule.getRevision(), prefix, name);
+            ModuleBuilder dependentModule = findDependentModule(modules, module, prefix, idref.getLine());
+            result = new QName(dependentModule.getNamespace(), dependentModule.getRevision(), prefix, name);
         } else {
-            result = new QName(module.getNamespace(), module.getRevision(),
-                    module.getPrefix(), baseString);
+            result = new QName(module.getNamespace(), module.getRevision(), module.getPrefix(), baseString);
         }
         return result;
     }
 
-    private void resolveUnknownNodes(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            final ModuleBuilder module) {
+    private void resolveUnknownNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final ModuleBuilder module) {
         for (UnknownSchemaNodeBuilder usnb : module.getUnknownNodes()) {
             QName nodeType = usnb.getNodeType();
-            if (nodeType.getNamespace() == null
-                    || nodeType.getRevision() == null) {
+            if (nodeType.getNamespace() == null || nodeType.getRevision() == null) {
                 try {
-                    ModuleBuilder dependentModule = findDependentModule(
-                            modules, module, nodeType.getPrefix(),
+                    ModuleBuilder dependentModule = findDependentModule(modules, module, nodeType.getPrefix(),
                             usnb.getLine());
-                    QName newNodeType = new QName(
-                            dependentModule.getNamespace(),
-                            dependentModule.getRevision(),
+                    QName newNodeType = new QName(dependentModule.getNamespace(), dependentModule.getRevision(),
                             nodeType.getPrefix(), nodeType.getLocalName());
                     usnb.setNodeType(newNodeType);
                 } catch (YangParseException e) {
-                    logger.debug(module.getName(), usnb.getLine(),
-                            "Failed to find unknown node type: " + nodeType);
+                    logger.debug(module.getName(), usnb.getLine(), "Failed to find unknown node type: " + nodeType);
                 }
             }
         }
@@ -1040,8 +917,7 @@ public final class YangParserImpl implements YangModelParser {
      *            current line in yang model
      * @return
      */
-    private ModuleBuilder findDependentModule(
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+    private ModuleBuilder findDependentModule(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final ModuleBuilder module, final String prefix, final int line) {
         ModuleBuilder dependentModule = null;
         Date dependentModuleRevision = null;
@@ -1049,37 +925,28 @@ public final class YangParserImpl implements YangModelParser {
         if (prefix.equals(module.getPrefix())) {
             dependentModule = module;
         } else {
-            final ModuleImport dependentModuleImport = ParserUtils
-                    .getModuleImport(module, prefix);
+            final ModuleImport dependentModuleImport = ParserUtils.getModuleImport(module, prefix);
             if (dependentModuleImport == null) {
-                throw new YangParseException(module.getName(), line,
-                        "No import found with prefix '" + prefix + "'.");
+                throw new YangParseException(module.getName(), line, "No import found with prefix '" + prefix + "'.");
             }
-            final String dependentModuleName = dependentModuleImport
-                    .getModuleName();
+            final String dependentModuleName = dependentModuleImport.getModuleName();
             dependentModuleRevision = dependentModuleImport.getRevision();
 
-            final TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules
-                    .get(dependentModuleName);
+            final TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
             if (moduleBuildersByRevision == null) {
-                throw new YangParseException(module.getName(), line,
-                        "Failed to find dependent module '"
-                                + dependentModuleName + "'.");
+                throw new YangParseException(module.getName(), line, "Failed to find dependent module '"
+                        + dependentModuleName + "'.");
             }
             if (dependentModuleRevision == null) {
-                dependentModule = moduleBuildersByRevision.lastEntry()
-                        .getValue();
+                dependentModule = moduleBuildersByRevision.lastEntry().getValue();
             } else {
-                dependentModule = moduleBuildersByRevision
-                        .get(dependentModuleRevision);
+                dependentModule = moduleBuildersByRevision.get(dependentModuleRevision);
             }
         }
 
         if (dependentModule == null) {
-            throw new YangParseException(module.getName(), line,
-                    "Failed to find dependent module with prefix '" + prefix
-                            + "' and revision '" + dependentModuleRevision
-                            + "'.");
+            throw new YangParseException(module.getName(), line, "Failed to find dependent module with prefix '"
+                    + prefix + "' and revision '" + dependentModuleRevision + "'.");
         }
         return dependentModule;
     }
index 1c01cd4a82b56cdbc016ed0e3f0c23eec5b833d8..5bd46d1231aaa8f3bacad6b67efec62c7a6c87c5 100644 (file)
@@ -81,19 +81,15 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public final class YangParserListenerImpl extends YangParserBaseListener {
-
-    private static final Logger logger = LoggerFactory
-            .getLogger(YangParserListenerImpl.class);
+    private static final Logger logger = LoggerFactory.getLogger(YangParserListenerImpl.class);
 
     private ModuleBuilder moduleBuilder;
-
     private String moduleName;
     private URI namespace;
     private String yangModelPrefix;
     private Date revision = new Date(0L);
 
-    public final static DateFormat simpleDateFormat = new SimpleDateFormat(
-            "yyyy-MM-dd");
+    public final static DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
     private final Stack<String> actualPath = new Stack<String>();
 
     @Override
@@ -173,8 +169,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     }
 
     @Override
-    public void exitSubmodule_header_stmts(
-            YangParser.Submodule_header_stmtsContext ctx) {
+    public void exitSubmodule_header_stmts(YangParser.Submodule_header_stmtsContext ctx) {
         final String submodule = actualPath.pop();
         logger.debug("exiting submodule " + submodule);
     }
@@ -206,8 +201,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                 }
             }
         } catch (ParseException e) {
-            final String message = "Failed to parse revision string: "
-                    + revisionDateStr;
+            final String message = "Failed to parse revision string: " + revisionDateStr;
             logger.warn(message);
         }
     }
@@ -228,8 +222,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                 try {
                     importRevision = simpleDateFormat.parse(importRevisionStr);
                 } catch (ParseException e) {
-                    logger.warn("Failed to parse import revision-date: "
-                            + importRevisionStr);
+                    logger.warn("Failed to parse import revision-date: " + importRevisionStr);
                 }
             }
         }
@@ -239,8 +232,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterAugment_stmt(YangParser.Augment_stmtContext ctx) {
         final String augmentPath = stringFromNode(ctx);
-        AugmentationSchemaBuilder builder = moduleBuilder.addAugment(
-                augmentPath, actualPath, ctx.getStart().getLine());
+        AugmentationSchemaBuilder builder = moduleBuilder.addAugment(augmentPath, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(augmentPath);
 
@@ -273,8 +265,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     public void enterExtension_stmt(YangParser.Extension_stmtContext ctx) {
         final String extName = stringFromNode(ctx);
         QName qname = new QName(namespace, revision, yangModelPrefix, extName);
-        ExtensionBuilder builder = moduleBuilder.addExtension(qname, ctx
-                .getStart().getLine());
+        ExtensionBuilder builder = moduleBuilder.addExtension(qname, ctx.getStart().getLine());
         parseSchemaNodeArgs(ctx, builder);
 
         String argument = null;
@@ -294,15 +285,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterTypedef_stmt(YangParser.Typedef_stmtContext ctx) {
         final String typedefName = stringFromNode(ctx);
-        QName typedefQName = new QName(namespace, revision, yangModelPrefix,
-                typedefName);
-        TypeDefinitionBuilder builder = moduleBuilder.addTypedef(typedefQName,
-                actualPath, ctx.getStart().getLine());
+        QName typedefQName = new QName(namespace, revision, yangModelPrefix, typedefName);
+        TypeDefinitionBuilder builder = moduleBuilder.addTypedef(typedefQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(typedefName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         builder.setUnits(parseUnits(ctx));
     }
@@ -335,35 +323,27 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                 // check for types which must have body
                 checkMissingBody(typeName, moduleName, line);
                 // if there are no constraints, just grab default base yang type
-                type = YangTypesConverter.javaTypeForBaseYangType(actualPath,
-                        namespace, revision, typeName);
+                type = YangTypesConverter.javaTypeForBaseYangType(actualPath, namespace, revision, typeName);
                 moduleBuilder.setType(type, actualPath);
             } else {
                 if ("union".equals(typeName)) {
                     List<String> typePath = new ArrayList<String>(actualPath);
                     typePath.add(typeName);
-                    SchemaPath p = createActualSchemaPath(typePath, namespace,
-                            revision, yangModelPrefix);
-                    UnionTypeBuilder unionBuilder = moduleBuilder.addUnionType(
-                            actualPath, namespace, revision, line);
+                    SchemaPath p = createActualSchemaPath(typePath, namespace, revision, yangModelPrefix);
+                    UnionTypeBuilder unionBuilder = moduleBuilder.addUnionType(actualPath, namespace, revision, line);
                     moduleBuilder.enterNode(unionBuilder);
                     unionBuilder.setPath(p);
                 } else if ("identityref".equals(typeName)) {
-                    SchemaPath path = createActualSchemaPath(actualPath,
-                            namespace, revision, yangModelPrefix);
-                    moduleBuilder.addIdentityrefType(
-                            getIdentityrefBase(typeBody), actualPath, path,
-                            line);
+                    SchemaPath path = createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix);
+                    moduleBuilder.addIdentityrefType(getIdentityrefBase(typeBody), actualPath, path, line);
                 } else {
-                    type = parseTypeBody(typeName, typeBody, actualPath,
-                            namespace, revision, yangModelPrefix,
-                            moduleBuilder.getActualNode());
+                    type = parseTypeBody(moduleName, typeName, typeBody, actualPath, namespace, revision,
+                            yangModelPrefix, moduleBuilder.getActualNode());
                     moduleBuilder.setType(type, actualPath);
                 }
             }
         } else {
-            type = parseUnknownTypeBody(typeQName, typeBody, actualPath,
-                    namespace, revision, yangModelPrefix,
+            type = parseUnknownTypeBody(typeQName, typeBody, actualPath, namespace, revision, yangModelPrefix,
                     moduleBuilder.getActualNode(), moduleBuilder);
             // mark parent node of this type statement as dirty
             moduleBuilder.addDirtyNode(actualPath);
@@ -385,8 +365,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                 typeQName = new QName(null, null, prefix, name);
             }
         } else {
-            typeQName = new QName(namespace, revision, yangModelPrefix,
-                    typeName);
+            typeQName = new QName(namespace, revision, yangModelPrefix, typeName);
         }
         return typeQName;
     }
@@ -405,14 +384,11 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterGrouping_stmt(YangParser.Grouping_stmtContext ctx) {
         final String groupName = stringFromNode(ctx);
-        QName groupQName = new QName(namespace, revision, yangModelPrefix,
-                groupName);
-        GroupingBuilder builder = moduleBuilder.addGrouping(groupQName,
-                actualPath, ctx.getStart().getLine());
+        QName groupQName = new QName(namespace, revision, yangModelPrefix, groupName);
+        GroupingBuilder builder = moduleBuilder.addGrouping(groupQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(groupName);
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
     }
 
@@ -426,15 +402,13 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterContainer_stmt(Container_stmtContext ctx) {
         final String containerName = stringFromNode(ctx);
-        QName containerQName = new QName(namespace, revision, yangModelPrefix,
-                containerName);
-        ContainerSchemaNodeBuilder builder = moduleBuilder.addContainerNode(
-                containerQName, actualPath, ctx.getStart().getLine());
+        QName containerQName = new QName(namespace, revision, yangModelPrefix, containerName);
+        ContainerSchemaNodeBuilder builder = moduleBuilder.addContainerNode(containerQName, actualPath, ctx.getStart()
+                .getLine());
         moduleBuilder.enterNode(builder);
         updatePath(containerName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
 
@@ -457,15 +431,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterLeaf_stmt(Leaf_stmtContext ctx) {
         final String leafName = stringFromNode(ctx);
-        QName leafQName = new QName(namespace, revision, yangModelPrefix,
-                leafName);
-        LeafSchemaNodeBuilder builder = moduleBuilder.addLeafNode(leafQName,
-                actualPath, ctx.getStart().getLine());
+        QName leafQName = new QName(namespace, revision, yangModelPrefix, leafName);
+        LeafSchemaNodeBuilder builder = moduleBuilder.addLeafNode(leafQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(leafName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
 
@@ -493,13 +464,11 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterUses_stmt(YangParser.Uses_stmtContext ctx) {
         final String groupingPathStr = stringFromNode(ctx);
-        UsesNodeBuilder builder = moduleBuilder.addUsesNode(groupingPathStr,
-                actualPath, ctx.getStart().getLine());
+        UsesNodeBuilder builder = moduleBuilder.addUsesNode(groupingPathStr, actualPath, ctx.getStart().getLine());
 
         moduleBuilder.enterNode(builder);
         updatePath(groupingPathStr);
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
     }
 
     @Override
@@ -528,15 +497,13 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterLeaf_list_stmt(Leaf_list_stmtContext ctx) {
         final String leafListName = stringFromNode(ctx);
-        QName leafListQName = new QName(namespace, revision, yangModelPrefix,
-                leafListName);
-        LeafListSchemaNodeBuilder builder = moduleBuilder.addLeafListNode(
-                leafListQName, actualPath, ctx.getStart().getLine());
+        QName leafListQName = new QName(namespace, revision, yangModelPrefix, leafListName);
+        LeafListSchemaNodeBuilder builder = moduleBuilder.addLeafListNode(leafListQName, actualPath, ctx.getStart()
+                .getLine());
         moduleBuilder.enterNode(builder);
         updatePath(leafListName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
 
@@ -561,15 +528,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterList_stmt(List_stmtContext ctx) {
         final String containerName = stringFromNode(ctx);
-        QName containerQName = new QName(namespace, revision, yangModelPrefix,
-                containerName);
-        ListSchemaNodeBuilder builder = moduleBuilder.addListNode(
-                containerQName, actualPath, ctx.getStart().getLine());
+        QName containerQName = new QName(namespace, revision, yangModelPrefix, containerName);
+        ListSchemaNodeBuilder builder = moduleBuilder.addListNode(containerQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(containerName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
 
@@ -582,8 +546,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
                 builder.setUserOrdered(userOrdered);
             } else if (childNode instanceof Key_stmtContext) {
                 keyDefinition = stringFromNode(childNode);
-                List<QName> key = createListKey(keyDefinition, namespace,
-                        revision, yangModelPrefix);
+                List<QName> key = createListKey(keyDefinition, namespace, revision, yangModelPrefix);
                 builder.setKeyDefinition(key);
             }
         }
@@ -599,15 +562,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterAnyxml_stmt(YangParser.Anyxml_stmtContext ctx) {
         final String anyXmlName = stringFromNode(ctx);
-        QName anyXmlQName = new QName(namespace, revision, yangModelPrefix,
-                anyXmlName);
-        AnyXmlBuilder builder = moduleBuilder.addAnyXml(anyXmlQName,
-                actualPath, ctx.getStart().getLine());
+        QName anyXmlQName = new QName(namespace, revision, yangModelPrefix, anyXmlName);
+        AnyXmlBuilder builder = moduleBuilder.addAnyXml(anyXmlQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(anyXmlName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
     }
@@ -622,15 +582,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterChoice_stmt(YangParser.Choice_stmtContext ctx) {
         final String choiceName = stringFromNode(ctx);
-        QName choiceQName = new QName(namespace, revision, yangModelPrefix,
-                choiceName);
-        ChoiceBuilder builder = moduleBuilder.addChoice(choiceQName,
-                actualPath, ctx.getStart().getLine());
+        QName choiceQName = new QName(namespace, revision, yangModelPrefix, choiceName);
+        ChoiceBuilder builder = moduleBuilder.addChoice(choiceQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
 
         updatePath(choiceName);
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
 
@@ -655,15 +612,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterCase_stmt(YangParser.Case_stmtContext ctx) {
         final String caseName = stringFromNode(ctx);
-        QName choiceQName = new QName(namespace, revision, yangModelPrefix,
-                caseName);
-        ChoiceCaseBuilder builder = moduleBuilder.addCase(choiceQName,
-                actualPath, ctx.getStart().getLine());
+        QName choiceQName = new QName(namespace, revision, yangModelPrefix, caseName);
+        ChoiceCaseBuilder builder = moduleBuilder.addCase(choiceQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
 
         updatePath(caseName);
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
     }
@@ -678,15 +632,13 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterNotification_stmt(YangParser.Notification_stmtContext ctx) {
         final String notificationName = stringFromNode(ctx);
-        QName notificationQName = new QName(namespace, revision,
-                yangModelPrefix, notificationName);
-        NotificationBuilder builder = moduleBuilder.addNotification(
-                notificationQName, actualPath, ctx.getStart().getLine());
+        QName notificationQName = new QName(namespace, revision, yangModelPrefix, notificationName);
+        NotificationBuilder builder = moduleBuilder.addNotification(notificationQName, actualPath, ctx.getStart()
+                .getLine());
         moduleBuilder.enterNode(builder);
         updatePath(notificationName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
     }
 
@@ -706,11 +658,9 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         final String nodeTypeStr = ctx.getChild(0).getText();
         final String[] splittedElement = nodeTypeStr.split(":");
         if (splittedElement.length == 1) {
-            nodeType = new QName(null, null, yangModelPrefix,
-                    splittedElement[0]);
+            nodeType = new QName(null, null, yangModelPrefix, splittedElement[0]);
         } else {
-            nodeType = new QName(null, null, splittedElement[0],
-                    splittedElement[1]);
+            nodeType = new QName(null, null, splittedElement[0], splittedElement[1]);
         }
 
         QName qname;
@@ -719,21 +669,18 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
             if (splittedName.length == 2) {
                 qname = new QName(null, null, splittedName[0], splittedName[1]);
             } else {
-                qname = new QName(namespace, revision, yangModelPrefix,
-                        splittedName[0]);
+                qname = new QName(namespace, revision, yangModelPrefix, splittedName[0]);
             }
         } else {
-            qname = new QName(namespace, revision, yangModelPrefix,
-                    nodeParameter);
+            qname = new QName(namespace, revision, yangModelPrefix, nodeParameter);
         }
 
-        UnknownSchemaNodeBuilder builder = moduleBuilder.addUnknownSchemaNode(
-                qname, actualPath, ctx.getStart().getLine());
+        UnknownSchemaNodeBuilder builder = moduleBuilder.addUnknownSchemaNode(qname, actualPath, ctx.getStart()
+                .getLine());
         builder.setNodeType(nodeType);
         builder.setNodeParameter(nodeParameter);
         updatePath(nodeParameter);
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         moduleBuilder.enterNode(builder);
     }
@@ -748,15 +695,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterRpc_stmt(YangParser.Rpc_stmtContext ctx) {
         final String rpcName = stringFromNode(ctx);
-        QName rpcQName = new QName(namespace, revision, yangModelPrefix,
-                rpcName);
-        RpcDefinitionBuilder rpcBuilder = moduleBuilder.addRpc(rpcQName,
-                actualPath, ctx.getStart().getLine());
+        QName rpcQName = new QName(namespace, revision, yangModelPrefix, rpcName);
+        RpcDefinitionBuilder rpcBuilder = moduleBuilder.addRpc(rpcQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(rpcBuilder);
         updatePath(rpcName);
 
-        rpcBuilder.setPath(createActualSchemaPath(actualPath, namespace,
-                revision, yangModelPrefix));
+        rpcBuilder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, rpcBuilder);
     }
 
@@ -771,13 +715,11 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     public void enterInput_stmt(YangParser.Input_stmtContext ctx) {
         final String input = "input";
         QName rpcQName = new QName(namespace, revision, yangModelPrefix, input);
-        ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcInput(
-                rpcQName, ctx.getStart().getLine());
+        ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcInput(rpcQName, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(input);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
     }
@@ -793,13 +735,11 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     public void enterOutput_stmt(YangParser.Output_stmtContext ctx) {
         final String output = "output";
         QName rpcQName = new QName(namespace, revision, yangModelPrefix, output);
-        ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcOutput(
-                rpcQName, ctx.getStart().getLine());
+        ContainerSchemaNodeBuilder builder = moduleBuilder.addRpcOutput(rpcQName, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(output);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
         parseConstraints(ctx, builder.getConstraints());
     }
@@ -814,15 +754,12 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterFeature_stmt(YangParser.Feature_stmtContext ctx) {
         final String featureName = stringFromNode(ctx);
-        QName featureQName = new QName(namespace, revision, yangModelPrefix,
-                featureName);
-        FeatureBuilder featureBuilder = moduleBuilder.addFeature(featureQName,
-                actualPath, ctx.getStart().getLine());
+        QName featureQName = new QName(namespace, revision, yangModelPrefix, featureName);
+        FeatureBuilder featureBuilder = moduleBuilder.addFeature(featureQName, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(featureBuilder);
         updatePath(featureName);
 
-        featureBuilder.setPath(createActualSchemaPath(actualPath, namespace,
-                revision, yangModelPrefix));
+        featureBuilder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, featureBuilder);
     }
 
@@ -838,8 +775,7 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
         final String targetPath = stringFromNode(ctx);
         String reference = null;
         String deviate = null;
-        DeviationBuilder builder = moduleBuilder.addDeviation(targetPath,
-                actualPath, ctx.getStart().getLine());
+        DeviationBuilder builder = moduleBuilder.addDeviation(targetPath, actualPath, ctx.getStart().getLine());
         moduleBuilder.enterNode(builder);
         updatePath(targetPath);
 
@@ -871,22 +807,19 @@ public final class YangParserListenerImpl extends YangParserBaseListener {
     @Override
     public void enterConfig_stmt(YangParser.Config_stmtContext ctx) {
         boolean configuration = parseConfig(ctx);
-        moduleBuilder.addConfiguration(configuration, actualPath, ctx
-                .getStart().getLine());
+        moduleBuilder.addConfiguration(configuration, actualPath, ctx.getStart().getLine());
     }
 
     @Override
     public void enterIdentity_stmt(YangParser.Identity_stmtContext ctx) {
         final String identityName = stringFromNode(ctx);
-        final QName identityQName = new QName(namespace, revision,
-                yangModelPrefix, identityName);
-        IdentitySchemaNodeBuilder builder = moduleBuilder.addIdentity(
-                identityQName, actualPath, ctx.getStart().getLine());
+        final QName identityQName = new QName(namespace, revision, yangModelPrefix, identityName);
+        IdentitySchemaNodeBuilder builder = moduleBuilder.addIdentity(identityQName, actualPath, ctx.getStart()
+                .getLine());
         moduleBuilder.enterNode(builder);
         updatePath(identityName);
 
-        builder.setPath(createActualSchemaPath(actualPath, namespace, revision,
-                yangModelPrefix));
+        builder.setPath(createActualSchemaPath(actualPath, namespace, revision, yangModelPrefix));
         parseSchemaNodeArgs(ctx, builder);
 
         for (int i = 0; i < ctx.getChildCount(); i++) {
index 670c1d573c9b46de1df4f3085b39716a63695818..17307b46ee29f8aedc8a8dcc58e4113a1d9c84f2 100644 (file)
@@ -20,17 +20,24 @@ import org.opendaylight.controller.yang.model.util.BaseConstraints;
  * Holder object for holding YANG type constraints.
  */
 public final class TypeConstraints {
+    private final String moduleName;
+    private final int line;
     private final List<List<RangeConstraint>> ranges = new ArrayList<List<RangeConstraint>>();
     private final List<List<LengthConstraint>> lengths = new ArrayList<List<LengthConstraint>>();
     private final List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
     private final List<Integer> fractionDigits = new ArrayList<Integer>();
 
+    public TypeConstraints(final String moduleName, final int line) {
+        this.moduleName = moduleName;
+        this.line = line;
+    }
+
     List<List<RangeConstraint>> getAllRanges() {
         return ranges;
     }
 
     public List<RangeConstraint> getRange() {
-        if (ranges.isEmpty()) {
+        if (ranges.size() < 2) {
             return Collections.emptyList();
         }
 
@@ -40,8 +47,10 @@ public final class TypeConstraints {
         Number min = firstRange.getMin();
         Number max = lastRange.getMax();
 
-        if (!(min instanceof UnknownBoundaryNumber)
-                && !(max instanceof UnknownBoundaryNumber)) {
+        if (!(min instanceof UnknownBoundaryNumber) && !(max instanceof UnknownBoundaryNumber)) {
+            if (ranges.size() > 1) {
+                validateRange(resolved);
+            }
             return resolved;
         }
 
@@ -52,28 +61,28 @@ public final class TypeConstraints {
             if (max instanceof UnknownBoundaryNumber) {
                 max = resolveMaxRange(max);
             }
-            firstRange = BaseConstraints.rangeConstraint(min, max,
-                    firstRange.getDescription(), firstRange.getReference());
+            firstRange = BaseConstraints.rangeConstraint(min, max, firstRange.getDescription(),
+                    firstRange.getReference());
             resolved.set(0, firstRange);
-            lastRange = BaseConstraints.rangeConstraint(min, max,
-                    lastRange.getDescription(), lastRange.getReference());
+            lastRange = BaseConstraints.rangeConstraint(min, max, lastRange.getDescription(), lastRange.getReference());
             resolved.set(resolved.size() - 1, lastRange);
         } else {
             if (min instanceof UnknownBoundaryNumber) {
                 min = resolveMinRange(min);
-                firstRange = BaseConstraints.rangeConstraint(min,
-                        firstRange.getMax(), firstRange.getDescription(),
+                firstRange = BaseConstraints.rangeConstraint(min, firstRange.getMax(), firstRange.getDescription(),
                         firstRange.getReference());
                 resolved.set(0, firstRange);
             }
             if (max instanceof UnknownBoundaryNumber) {
                 max = resolveMaxRange(max);
-                lastRange = BaseConstraints.rangeConstraint(lastRange.getMin(),
-                        max, lastRange.getDescription(),
+                lastRange = BaseConstraints.rangeConstraint(lastRange.getMin(), max, lastRange.getDescription(),
                         lastRange.getReference());
                 resolved.set(resolved.size() - 1, lastRange);
             }
         }
+        if (this.ranges.size() > 1) {
+            validateRange(resolved);
+        }
         return resolved;
     }
 
@@ -108,7 +117,7 @@ public final class TypeConstraints {
     }
 
     public List<LengthConstraint> getLength() {
-        if (lengths.isEmpty()) {
+        if (lengths.size() < 2) {
             return Collections.emptyList();
         }
 
@@ -118,8 +127,10 @@ public final class TypeConstraints {
         Number min = firstLength.getMin();
         Number max = lastLength.getMax();
 
-        if (!(min instanceof UnknownBoundaryNumber)
-                && !(max instanceof UnknownBoundaryNumber)) {
+        if (!(min instanceof UnknownBoundaryNumber) && !(max instanceof UnknownBoundaryNumber)) {
+            if (lengths.size() > 1) {
+                validateLength(resolved);
+            }
             return resolved;
         }
 
@@ -130,28 +141,30 @@ public final class TypeConstraints {
             if (max instanceof UnknownBoundaryNumber) {
                 max = resolveMaxLength(max);
             }
-            firstLength = BaseConstraints.lengthConstraint(min, max,
-                    firstLength.getDescription(), firstLength.getReference());
+            firstLength = BaseConstraints.lengthConstraint(min, max, firstLength.getDescription(),
+                    firstLength.getReference());
             resolved.set(0, firstLength);
-            lastLength = BaseConstraints.lengthConstraint(min, max,
-                    lastLength.getDescription(), lastLength.getReference());
+            lastLength = BaseConstraints.lengthConstraint(min, max, lastLength.getDescription(),
+                    lastLength.getReference());
             resolved.set(resolved.size() - 1, lastLength);
         } else {
             if (min instanceof UnknownBoundaryNumber) {
                 min = resolveMinLength(min);
-                firstLength = BaseConstraints.lengthConstraint(min,
-                        firstLength.getMax(), firstLength.getDescription(),
+                firstLength = BaseConstraints.lengthConstraint(min, firstLength.getMax(), firstLength.getDescription(),
                         firstLength.getReference());
                 resolved.set(0, firstLength);
             }
             if (max instanceof UnknownBoundaryNumber) {
                 max = resolveMaxLength(max);
-                lastLength = BaseConstraints.lengthConstraint(
-                        lastLength.getMin(), max, lastLength.getDescription(),
+                lastLength = BaseConstraints.lengthConstraint(lastLength.getMin(), max, lastLength.getDescription(),
                         lastLength.getReference());
                 resolved.set(resolved.size() - 1, lastLength);
             }
         }
+
+        if (lengths.size() > 1) {
+            validateLength(resolved);
+        }
         return resolved;
     }
 
@@ -200,4 +213,167 @@ public final class TypeConstraints {
         this.fractionDigits.add(fractionDigits);
     }
 
+    public void validateConstraints() {
+        validateLength();
+        validateRange();
+    }
+
+    private void validateRange() {
+        if (ranges.size() < 2) {
+            return;
+        }
+        List<RangeConstraint> typeRange = getRange();
+
+        for (RangeConstraint range : typeRange) {
+            if (range.getMin() instanceof UnknownBoundaryNumber || range.getMax() instanceof UnknownBoundaryNumber) {
+                throw new YangParseException(line, "Unresolved range constraints");
+            }
+            final long min = range.getMin().longValue();
+            final long max = range.getMax().longValue();
+
+            List<RangeConstraint> parentRanges = ranges.get(1);
+            boolean check = false;
+            for (RangeConstraint r : parentRanges) {
+                Number parentMinNumber = r.getMin();
+                if (parentMinNumber instanceof UnknownBoundaryNumber) {
+                    parentMinNumber = resolveMinRange(parentMinNumber);
+                }
+                long parentMin = parentMinNumber.longValue();
+
+                Number parentMaxNumber = r.getMax();
+                if (parentMaxNumber instanceof UnknownBoundaryNumber) {
+                    parentMaxNumber = resolveMaxRange(parentMaxNumber);
+                }
+                long parentMax = parentMaxNumber.longValue();
+
+                if (parentMin <= min && parentMax >= max) {
+                    check = true;
+                    break;
+                }
+            }
+            if (!check) {
+                throw new YangParseException(moduleName, line, "Invalid range constraint: <" + min + ", " + max
+                        + "> (parent: " + parentRanges + ").");
+            }
+        }
+    }
+
+    private void validateRange(List<RangeConstraint> typeRange) {
+        if (ranges.size() < 2) {
+            return;
+        }
+
+        for (RangeConstraint range : typeRange) {
+            if (range.getMin() instanceof UnknownBoundaryNumber || range.getMax() instanceof UnknownBoundaryNumber) {
+                throw new YangParseException(line, "Unresolved range constraints");
+            }
+            final long min = range.getMin().longValue();
+            final long max = range.getMax().longValue();
+
+            List<RangeConstraint> parentRanges = ranges.get(1);
+            boolean check = false;
+            for (RangeConstraint r : parentRanges) {
+                Number parentMinNumber = r.getMin();
+                if (parentMinNumber instanceof UnknownBoundaryNumber) {
+                    parentMinNumber = resolveMinRange(parentMinNumber);
+                }
+                long parentMin = parentMinNumber.longValue();
+
+                Number parentMaxNumber = r.getMax();
+                if (parentMaxNumber instanceof UnknownBoundaryNumber) {
+                    parentMaxNumber = resolveMaxRange(parentMaxNumber);
+                }
+                long parentMax = parentMaxNumber.longValue();
+
+                if (parentMin <= min && parentMax >= max) {
+                    check = true;
+                    break;
+                }
+            }
+            if (!check) {
+                throw new YangParseException(moduleName, line, "Invalid range constraint: <" + min + ", " + max
+                        + "> (parent: " + parentRanges + ").");
+            }
+        }
+    }
+
+    private void validateLength() {
+        if (lengths.size() < 2) {
+            return;
+        }
+        List<LengthConstraint> typeLength = getLength();
+
+        for (LengthConstraint length : typeLength) {
+            if (length.getMin() instanceof UnknownBoundaryNumber || length.getMax() instanceof UnknownBoundaryNumber) {
+                throw new YangParseException(line, "Unresolved length constraints");
+            }
+            final long min = length.getMin().longValue();
+            final long max = length.getMax().longValue();
+
+            List<LengthConstraint> parentLengths = lengths.get(1);
+            boolean check = false;
+            for (LengthConstraint lc : parentLengths) {
+                Number parentMinNumber = lc.getMin();
+                if (parentMinNumber instanceof UnknownBoundaryNumber) {
+                    parentMinNumber = resolveMinLength(parentMinNumber);
+                }
+                long parentMin = parentMinNumber.longValue();
+
+                Number parentMaxNumber = lc.getMax();
+                if (parentMaxNumber instanceof UnknownBoundaryNumber) {
+                    parentMaxNumber = resolveMaxLength(parentMaxNumber);
+                }
+                long parentMax = parentMaxNumber.longValue();
+
+                if (parentMin <= min && parentMax >= max) {
+                    check = true;
+                    break;
+                }
+            }
+            if (!check) {
+                throw new YangParseException(moduleName, line, "Invalid length constraint: <" + min + ", " + max
+                        + "> (parent: " + parentLengths + ").");
+            }
+        }
+    }
+
+    private void validateLength(List<LengthConstraint> typeLength) {
+        if (lengths.size() < 2) {
+            return;
+        }
+
+        for (LengthConstraint length : typeLength) {
+            if (length.getMin() instanceof UnknownBoundaryNumber || length.getMax() instanceof UnknownBoundaryNumber) {
+                throw new YangParseException(line, "Unresolved length constraints");
+            }
+            final long min = length.getMin().longValue();
+            final long max = length.getMax().longValue();
+
+            List<LengthConstraint> parentLengths = lengths.get(1);
+            boolean check = false;
+            for (LengthConstraint lc : parentLengths) {
+                Number parentMinNumber = lc.getMin();
+                if (parentMinNumber instanceof UnknownBoundaryNumber) {
+                    parentMinNumber = resolveMinLength(parentMinNumber);
+                }
+                long parentMin = parentMinNumber.longValue();
+
+                Number parentMaxNumber = lc.getMax();
+                if (parentMaxNumber instanceof UnknownBoundaryNumber) {
+                    parentMaxNumber = resolveMaxLength(parentMaxNumber);
+                }
+                long parentMax = parentMaxNumber.longValue();
+
+                if (parentMin <= min && parentMax >= max) {
+                    check = true;
+                    break;
+                }
+            }
+            if (!check) {
+                throw new YangParseException(moduleName, line, "Invalid length constraint: <" + min + ", " + max
+                        + "> (parent: " + parentLengths + ").");
+            }
+        }
+    }
+
 }
index 1e55b2444919fd67f5f46dd2114e8610e3d9e07f..ae405c06a88805d0c744c1fb2a5b97f2c9dda9ec 100644 (file)
@@ -118,8 +118,7 @@ import org.slf4j.LoggerFactory;
 
 public final class YangModelBuilderUtil {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(YangModelBuilderUtil.class);
+    private static final Logger logger = LoggerFactory.getLogger(YangModelBuilderUtil.class);
 
     private YangModelBuilderUtil() {
     }
@@ -135,8 +134,7 @@ public final class YangModelBuilderUtil {
         final String result = "";
         for (int i = 0; i < treeNode.getChildCount(); ++i) {
             if (treeNode.getChild(i) instanceof StringContext) {
-                final StringContext context = (StringContext) treeNode
-                        .getChild(i);
+                final StringContext context = (StringContext) treeNode.getChild(i);
                 if (context != null) {
                     return context.getChild(0).getText().replace("\"", "");
                 }
@@ -154,8 +152,7 @@ public final class YangModelBuilderUtil {
      * @param builder
      *            builder to fill in with parsed statements
      */
-    public static void parseSchemaNodeArgs(final ParseTree ctx,
-            final SchemaNodeBuilder builder) {
+    public static void parseSchemaNodeArgs(final ParseTree ctx, final SchemaNodeBuilder builder) {
         for (int i = 0; i < ctx.getChildCount(); i++) {
             final ParseTree child = ctx.getChild(i);
             if (child instanceof Description_stmtContext) {
@@ -229,8 +226,7 @@ public final class YangModelBuilderUtil {
      * @param prefix
      * @return SchemaPath object.
      */
-    public static SchemaPath createActualSchemaPath(
-            final List<String> actualPath, final URI namespace,
+    public static SchemaPath createActualSchemaPath(final List<String> actualPath, final URI namespace,
             final Date revision, final String prefix) {
         final List<QName> path = new ArrayList<QName>();
         QName qname;
@@ -260,8 +256,7 @@ public final class YangModelBuilderUtil {
                 if (splittedElement.length == 1) {
                     name = new QName(null, null, null, splittedElement[0]);
                 } else {
-                    name = new QName(null, null, splittedElement[0],
-                            splittedElement[1]);
+                    name = new QName(null, null, splittedElement[0], splittedElement[1]);
                 }
                 path.add(name);
             }
@@ -283,8 +278,8 @@ public final class YangModelBuilderUtil {
      *            current prefix
      * @return YANG list key as java.util.List of QName objects
      */
-    public static List<QName> createListKey(final String keyDefinition,
-            final URI namespace, final Date revision, final String prefix) {
+    public static List<QName> createListKey(final String keyDefinition, final URI namespace, final Date revision,
+            final String prefix) {
         List<QName> key = new ArrayList<QName>();
         String[] splittedKey = keyDefinition.split(" ");
 
@@ -310,9 +305,8 @@ public final class YangModelBuilderUtil {
      * @param prefix
      * @return List of EnumPair object parsed from given context
      */
-    private static List<EnumTypeDefinition.EnumPair> getEnumConstants(
-            final Type_body_stmtsContext ctx, final List<String> path,
-            final URI namespace, final Date revision, final String prefix) {
+    private static List<EnumTypeDefinition.EnumPair> getEnumConstants(final Type_body_stmtsContext ctx,
+            final List<String> path, final URI namespace, final Date revision, final String prefix) {
         List<EnumTypeDefinition.EnumPair> enumConstants = new ArrayList<EnumTypeDefinition.EnumPair>();
 
         for (int j = 0; j < ctx.getChildCount(); j++) {
@@ -322,9 +316,8 @@ public final class YangModelBuilderUtil {
                 for (int k = 0; k < enumSpecChild.getChildCount(); k++) {
                     ParseTree enumChild = enumSpecChild.getChild(k);
                     if (enumChild instanceof Enum_stmtContext) {
-                        EnumPair enumPair = createEnumPair(
-                                (Enum_stmtContext) enumChild, highestValue,
-                                path, namespace, revision, prefix);
+                        EnumPair enumPair = createEnumPair((Enum_stmtContext) enumChild, highestValue, path, namespace,
+                                revision, prefix);
                         if (enumPair.getValue() > highestValue) {
                             highestValue = enumPair.getValue();
                         }
@@ -350,10 +343,8 @@ public final class YangModelBuilderUtil {
      * @param prefix
      * @return EnumPair object parsed from given context
      */
-    private static EnumTypeDefinition.EnumPair createEnumPair(
-            final Enum_stmtContext ctx, final int highestValue,
-            final List<String> path, final URI namespace, final Date revision,
-            final String prefix) {
+    private static EnumTypeDefinition.EnumPair createEnumPair(final Enum_stmtContext ctx, final int highestValue,
+            final List<String> path, final URI namespace, final Date revision, final String prefix) {
         final String name = stringFromNode(ctx);
         final QName qname = new QName(namespace, revision, prefix, name);
         Integer value = null;
@@ -383,18 +374,13 @@ public final class YangModelBuilderUtil {
             value = highestValue + 1;
         }
         if (value < -2147483648 || value > 2147483647) {
-            throw new YangParseException(
-                    ctx.getStart().getLine(),
-                    "Error on enum '"
-                            + name
-                            + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: "
-                            + value);
+            throw new YangParseException(ctx.getStart().getLine(), "Error on enum '" + name
+                    + "': the enum value MUST be in the range from -2147483648 to 2147483647, but was: " + value);
         }
 
         EnumPairImpl result = new EnumPairImpl();
         result.qname = qname;
-        result.path = createActualSchemaPath(enumPairPath, namespace, revision,
-                prefix);
+        result.path = createActualSchemaPath(enumPairPath, namespace, revision, prefix);
         result.description = description;
         result.reference = reference;
         result.status = status;
@@ -412,8 +398,7 @@ public final class YangModelBuilderUtil {
         private String description;
         private String reference;
         private Status status;
-        private List<UnknownSchemaNode> extensionSchemaNodes = Collections
-                .emptyList();
+        private List<UnknownSchemaNode> extensionSchemaNodes = Collections.emptyList();
         private String name;
         private Integer value;
 
@@ -463,10 +448,7 @@ public final class YangModelBuilderUtil {
             int result = 1;
             result = prime * result + ((qname == null) ? 0 : qname.hashCode());
             result = prime * result + ((path == null) ? 0 : path.hashCode());
-            result = prime
-                    * result
-                    + ((extensionSchemaNodes == null) ? 0
-                            : extensionSchemaNodes.hashCode());
+            result = prime * result + ((extensionSchemaNodes == null) ? 0 : extensionSchemaNodes.hashCode());
             result = prime * result + ((name == null) ? 0 : name.hashCode());
             result = prime * result + ((value == null) ? 0 : value.hashCode());
             return result;
@@ -524,8 +506,7 @@ public final class YangModelBuilderUtil {
 
         @Override
         public String toString() {
-            return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name="
-                    + name + ", value=" + value + "]";
+            return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
         }
     }
 
@@ -536,8 +517,7 @@ public final class YangModelBuilderUtil {
      *            type body context to parse
      * @return List of RangeConstraint created from this context
      */
-    private static List<RangeConstraint> getRangeConstraints(
-            final Type_body_stmtsContext ctx) {
+    private static List<RangeConstraint> getRangeConstraints(final Type_body_stmtsContext ctx) {
         List<RangeConstraint> rangeConstraints = Collections.emptyList();
         outer: for (int j = 0; j < ctx.getChildCount(); j++) {
             ParseTree numRestrChild = ctx.getChild(j);
@@ -561,8 +541,7 @@ public final class YangModelBuilderUtil {
      *            range context to parse
      * @return List of RangeConstraints parsed from this context
      */
-    private static List<RangeConstraint> parseRangeConstraints(
-            final Range_stmtContext ctx) {
+    private static List<RangeConstraint> parseRangeConstraints(final Range_stmtContext ctx) {
         final int line = ctx.getStart().getLine();
         List<RangeConstraint> rangeConstraints = new ArrayList<RangeConstraint>();
         String description = null;
@@ -585,14 +564,12 @@ public final class YangModelBuilderUtil {
             Number min;
             Number max;
             if (splittedRangeDef.length == 1) {
-                min = max = parseNumberConstraintValue(splittedRangeDef[0],
-                        line);
+                min = max = parseNumberConstraintValue(splittedRangeDef[0], line);
             } else {
                 min = parseNumberConstraintValue(splittedRangeDef[0], line);
                 max = parseNumberConstraintValue(splittedRangeDef[1], line);
             }
-            RangeConstraint range = BaseConstraints.rangeConstraint(min, max,
-                    description, reference);
+            RangeConstraint range = BaseConstraints.rangeConstraint(min, max, description, reference);
             rangeConstraints.add(range);
         }
 
@@ -606,8 +583,7 @@ public final class YangModelBuilderUtil {
      *            type body context to parse
      * @return List of LengthConstraint created from this context
      */
-    private static List<LengthConstraint> getLengthConstraints(
-            final Type_body_stmtsContext ctx) {
+    private static List<LengthConstraint> getLengthConstraints(final Type_body_stmtsContext ctx) {
         List<LengthConstraint> lengthConstraints = Collections.emptyList();
         outer: for (int j = 0; j < ctx.getChildCount(); j++) {
             ParseTree stringRestrChild = ctx.getChild(j);
@@ -631,8 +607,7 @@ public final class YangModelBuilderUtil {
      *            length context to parse
      * @return List of LengthConstraints parsed from this context
      */
-    private static List<LengthConstraint> parseLengthConstraints(
-            final Length_stmtContext ctx) {
+    private static List<LengthConstraint> parseLengthConstraints(final Length_stmtContext ctx) {
         final int line = ctx.getStart().getLine();
         List<LengthConstraint> lengthConstraints = new ArrayList<LengthConstraint>();
         String description = null;
@@ -655,14 +630,12 @@ public final class YangModelBuilderUtil {
             Number min;
             Number max;
             if (splittedRangeDef.length == 1) {
-                min = max = parseNumberConstraintValue(splittedRangeDef[0],
-                        line);
+                min = max = parseNumberConstraintValue(splittedRangeDef[0], line);
             } else {
                 min = parseNumberConstraintValue(splittedRangeDef[0], line);
                 max = parseNumberConstraintValue(splittedRangeDef[1], line);
             }
-            LengthConstraint range = BaseConstraints.lengthConstraint(min, max,
-                    description, reference);
+            LengthConstraint range = BaseConstraints.lengthConstraint(min, max, description, reference);
             lengthConstraints.add(range);
         }
 
@@ -675,8 +648,7 @@ public final class YangModelBuilderUtil {
      * @return wrapper object of primitive java type or UnknownBoundaryNumber if
      *         type is one of special YANG values 'min' or 'max'
      */
-    private static Number parseNumberConstraintValue(final String value,
-            final int line) {
+    private static Number parseNumberConstraintValue(final String value, final int line) {
         Number result = null;
         if ("min".equals(value) || "max".equals(value)) {
             result = new UnknownBoundaryNumber(value);
@@ -684,8 +656,7 @@ public final class YangModelBuilderUtil {
             try {
                 result = Long.valueOf(value);
             } catch (NumberFormatException e) {
-                throw new YangParseException(line,
-                        "Unable to parse range value '" + value + "'.", e);
+                throw new YangParseException(line, "Unable to parse range value '" + value + "'.", e);
             }
         }
         return result;
@@ -698,8 +669,7 @@ public final class YangModelBuilderUtil {
      *            type body
      * @return list of pattern constraints
      */
-    private static List<PatternConstraint> getPatternConstraint(
-            final Type_body_stmtsContext ctx) {
+    private static List<PatternConstraint> getPatternConstraint(final Type_body_stmtsContext ctx) {
         List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
 
         outer: for (int j = 0; j < ctx.getChildCount(); j++) {
@@ -726,8 +696,7 @@ public final class YangModelBuilderUtil {
      *            pattern context
      * @return PatternConstraint object
      */
-    private static PatternConstraint parsePatternConstraint(
-            final Pattern_stmtContext ctx) {
+    private static PatternConstraint parsePatternConstraint(final Pattern_stmtContext ctx) {
         String description = null;
         String reference = null;
         for (int i = 0; i < ctx.getChildCount(); i++) {
@@ -739,8 +708,7 @@ public final class YangModelBuilderUtil {
             }
         }
         String pattern = patternStringFromNode(ctx);
-        return BaseConstraints.patternConstraint(pattern, description,
-                reference);
+        return BaseConstraints.patternConstraint(pattern, description, reference);
     }
 
     /**
@@ -758,8 +726,7 @@ public final class YangModelBuilderUtil {
                 for (int j = 0; j < child.getChildCount(); j++) {
                     if (j % 2 == 0) {
                         String patternToken = child.getChild(j).getText();
-                        result.append(patternToken.substring(1,
-                                patternToken.length() - 1));
+                        result.append(patternToken.substring(1, patternToken.length() - 1));
                     }
                 }
             }
@@ -793,8 +760,7 @@ public final class YangModelBuilderUtil {
      *            decimal64 context
      * @return fraction-digits value as Integer
      */
-    private static Integer parseFractionDigits(
-            Decimal64_specificationContext ctx) {
+    private static Integer parseFractionDigits(Decimal64_specificationContext ctx) {
         Integer result = null;
         for (int k = 0; k < ctx.getChildCount(); k++) {
             ParseTree fdChild = ctx.getChild(k);
@@ -803,9 +769,8 @@ public final class YangModelBuilderUtil {
                 try {
                     result = Integer.valueOf(value);
                 } catch (NumberFormatException e) {
-                    throw new YangParseException(ctx.getStart().getLine(),
-                            "Unable to parse fraction digits value '" + value
-                                    + "'.", e);
+                    throw new YangParseException(ctx.getStart().getLine(), "Unable to parse fraction digits value '"
+                            + value + "'.", e);
                 }
             }
         }
@@ -825,9 +790,8 @@ public final class YangModelBuilderUtil {
      * @param prefix
      * @return List of Bit objects created from this context
      */
-    private static List<BitsTypeDefinition.Bit> getBits(
-            Type_body_stmtsContext ctx, List<String> actualPath, URI namespace,
-            Date revision, String prefix) {
+    private static List<BitsTypeDefinition.Bit> getBits(Type_body_stmtsContext ctx, List<String> actualPath,
+            URI namespace, Date revision, String prefix) {
         final List<BitsTypeDefinition.Bit> bits = new ArrayList<BitsTypeDefinition.Bit>();
         for (int j = 0; j < ctx.getChildCount(); j++) {
             ParseTree bitsSpecChild = ctx.getChild(j);
@@ -836,8 +800,7 @@ public final class YangModelBuilderUtil {
                 for (int k = 0; k < bitsSpecChild.getChildCount(); k++) {
                     ParseTree bitChild = bitsSpecChild.getChild(k);
                     if (bitChild instanceof Bit_stmtContext) {
-                        Bit bit = parseBit((Bit_stmtContext) bitChild,
-                                highestPosition, actualPath, namespace,
+                        Bit bit = parseBit((Bit_stmtContext) bitChild, highestPosition, actualPath, namespace,
                                 revision, prefix);
                         if (bit.getPosition() > highestPosition) {
                             highestPosition = bit.getPosition();
@@ -864,9 +827,8 @@ public final class YangModelBuilderUtil {
      * @param prefix
      * @return Bit object parsed from this context
      */
-    private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx,
-            long highestPosition, List<String> actualPath, final URI namespace,
-            final Date revision, final String prefix) {
+    private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, long highestPosition,
+            List<String> actualPath, final URI namespace, final Date revision, final String prefix) {
         String name = stringFromNode(ctx);
         final QName qname = new QName(namespace, revision, prefix, name);
         Long position = null;
@@ -879,8 +841,7 @@ public final class YangModelBuilderUtil {
         bitPath.addAll(actualPath);
         bitPath.add(name);
 
-        SchemaPath schemaPath = createActualSchemaPath(bitPath, namespace,
-                revision, prefix);
+        SchemaPath schemaPath = createActualSchemaPath(bitPath, namespace, revision, prefix);
 
         for (int i = 0; i < ctx.getChildCount(); i++) {
             ParseTree child = ctx.getChild(i);
@@ -900,16 +861,12 @@ public final class YangModelBuilderUtil {
             position = highestPosition + 1;
         }
         if (position < 0 || position > 4294967295L) {
-            throw new YangParseException(
-                    ctx.getStart().getLine(),
-                    "Error on bit '"
-                            + name
-                            + "': the position value MUST be in the range 0 to 4294967295");
+            throw new YangParseException(ctx.getStart().getLine(), "Error on bit '" + name
+                    + "': the position value MUST be in the range 0 to 4294967295");
         }
 
         final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
-        return new BitImpl(position, qname, schemaPath, description, reference,
-                status, unknownNodes);
+        return new BitImpl(position, qname, schemaPath, description, reference, status, unknownNodes);
     }
 
     /**
@@ -971,9 +928,8 @@ public final class YangModelBuilderUtil {
      *            type body
      * @return UnknownType object with constraints from parsed type body
      */
-    public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName,
-            Type_body_stmtsContext ctx, final List<String> actualPath,
-            final URI namespace, final Date revision, final String prefix,
+    public static TypeDefinition<?> parseUnknownTypeBody(QName typedefQName, Type_body_stmtsContext ctx,
+            final List<String> actualPath, final URI namespace, final Date revision, final String prefix,
             Builder parent, ModuleBuilder moduleBuilder) {
         String typeName = typedefQName.getLocalName();
 
@@ -998,10 +954,9 @@ public final class YangModelBuilderUtil {
                 QName qname = new QName(namespace, revision, prefix, typeName);
                 ExtendedType.Builder typeBuilder = null;
 
-                SchemaPath schemaPath = createTypeSchemaPath(actualPath,
-                        namespace, revision, prefix, typeName, false, false);
-                typeBuilder = new ExtendedType.Builder(qname, baseType, "", "",
-                        schemaPath);
+                SchemaPath schemaPath = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, false,
+                        false);
+                typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
 
                 typeBuilder.ranges(rangeStatements);
                 typeBuilder.lengths(lengthStatements);
@@ -1034,9 +989,8 @@ public final class YangModelBuilderUtil {
      *            current prefix
      * @return TypeDefinition object based on parsed values.
      */
-    public static TypeDefinition<?> parseTypeBody(final String typeName,
-            final Type_body_stmtsContext typeBody,
-            final List<String> actualPath, final URI namespace,
+    public static TypeDefinition<?> parseTypeBody(final String moduleName, final String typeName,
+            final Type_body_stmtsContext typeBody, final List<String> actualPath, final URI namespace,
             final Date revision, final String prefix, Builder parent) {
         TypeDefinition<?> baseType = null;
 
@@ -1044,19 +998,18 @@ public final class YangModelBuilderUtil {
         Integer fractionDigits = getFractionDigits(typeBody);
         List<LengthConstraint> lengthStatements = getLengthConstraints(typeBody);
         List<PatternConstraint> patternStatements = getPatternConstraint(typeBody);
-        List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(
-                typeBody, actualPath, namespace, revision, prefix);
+        List<EnumTypeDefinition.EnumPair> enumConstants = getEnumConstants(typeBody, actualPath, namespace, revision,
+                prefix);
 
-        TypeConstraints constraints = new TypeConstraints();
+        TypeConstraints constraints = new TypeConstraints(moduleName, typeBody.getStart().getLine());
         constraints.addFractionDigits(fractionDigits);
         constraints.addLengths(lengthStatements);
         constraints.addPatterns(patternStatements);
         constraints.addRanges(rangeStatements);
 
-        SchemaPath baseTypePathFinal = createTypeSchemaPath(actualPath,
-                namespace, revision, prefix, typeName, true, true);
-        SchemaPath baseTypePath = createTypeSchemaPath(actualPath, namespace,
-                revision, prefix, typeName, true, false);
+        SchemaPath baseTypePathFinal = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, true,
+                true);
+        SchemaPath baseTypePath = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, true, false);
 
         if ("decimal64".equals(typeName)) {
             if (rangeStatements.isEmpty()) {
@@ -1098,13 +1051,11 @@ public final class YangModelBuilderUtil {
             constraints.addLengths(stringType.getLengthStatements());
             baseType = stringType;
         } else if ("bits".equals(typeName)) {
-            return new BitsType(baseTypePathFinal, getBits(typeBody,
-                    actualPath, namespace, revision, prefix));
+            return new BitsType(baseTypePathFinal, getBits(typeBody, actualPath, namespace, revision, prefix));
         } else if ("leafref".equals(typeName)) {
             final String path = parseLeafrefPath(typeBody);
             final boolean absolute = path.startsWith("/");
-            RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path,
-                    absolute);
+            RevisionAwareXPath xpath = new RevisionAwareXPathImpl(path, absolute);
             return new Leafref(baseTypePathFinal, xpath);
         } else if ("binary".equals(typeName)) {
             BinaryTypeDefinition binaryType = new BinaryType(baseTypePath);
@@ -1112,12 +1063,10 @@ public final class YangModelBuilderUtil {
             baseType = binaryType;
         } else if ("instance-identifier".equals(typeName)) {
             boolean requireInstance = isRequireInstance(typeBody);
-            baseType = new InstanceIdentifier(baseTypePath, null,
-                    requireInstance);
+            baseType = new InstanceIdentifier(baseTypePath, null, requireInstance);
         }
 
-        if (parent instanceof TypeDefinitionBuilder
-                && !(parent instanceof UnionTypeBuilder)) {
+        if (parent instanceof TypeDefinitionBuilder && !(parent instanceof UnionTypeBuilder)) {
             TypeDefinitionBuilder typedef = (TypeDefinitionBuilder) parent;
             typedef.setRanges(constraints.getRange());
             typedef.setLengths(constraints.getLength());
@@ -1130,10 +1079,8 @@ public final class YangModelBuilderUtil {
         QName qname = new QName(namespace, revision, prefix, typeName);
         ExtendedType.Builder typeBuilder = null;
 
-        SchemaPath schemaPath = createTypeSchemaPath(actualPath, namespace,
-                revision, prefix, typeName, false, false);
-        typeBuilder = new ExtendedType.Builder(qname, baseType, "", "",
-                schemaPath);
+        SchemaPath schemaPath = createTypeSchemaPath(actualPath, namespace, revision, prefix, typeName, false, false);
+        typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
 
         typeBuilder.ranges(constraints.getRange());
         typeBuilder.lengths(constraints.getLength());
@@ -1160,10 +1107,9 @@ public final class YangModelBuilderUtil {
      *            if this is base yang type without restrictions
      * @return SchemaPath object.
      */
-    private static SchemaPath createTypeSchemaPath(
-            final List<String> actualPath, final URI namespace,
-            final Date revision, final String prefix, final String typeName,
-            final boolean isBaseYangType, final boolean isBaseYangTypeFinal) {
+    private static SchemaPath createTypeSchemaPath(final List<String> actualPath, final URI namespace,
+            final Date revision, final String prefix, final String typeName, final boolean isBaseYangType,
+            final boolean isBaseYangTypeFinal) {
         List<String> typePath = new ArrayList<String>(actualPath);
         if (isBaseYangType && !isBaseYangTypeFinal) {
             typePath.add(typeName);
@@ -1279,8 +1225,7 @@ public final class YangModelBuilderUtil {
                     for (int j = 0; j < context.getChildCount(); j++) {
                         String mustPart = context.getChild(j).getText();
                         if (j == 0) {
-                            mustText.append(mustPart.substring(0,
-                                    mustPart.length() - 1));
+                            mustText.append(mustPart.substring(0, mustPart.length() - 1));
                             continue;
                         }
                         if (j % 2 == 0) {
@@ -1299,8 +1244,8 @@ public final class YangModelBuilderUtil {
             }
         }
 
-        MustDefinition must = new MustDefinitionImpl(mustText.toString(),
-                description, reference, errorAppTag, errorMessage);
+        MustDefinition must = new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag,
+                errorMessage);
         return must;
     }
 
@@ -1312,8 +1257,7 @@ public final class YangModelBuilderUtil {
      * @param constraints
      *            ConstraintsBuilder to fill
      */
-    public static void parseConstraints(final ParseTree ctx,
-            final ConstraintsBuilder constraints) {
+    public static void parseConstraints(final ParseTree ctx, final ConstraintsBuilder constraints) {
         for (int i = 0; i < ctx.getChildCount(); ++i) {
             final ParseTree childNode = ctx.getChild(i);
             if (childNode instanceof Max_elements_stmtContext) {
@@ -1329,8 +1273,7 @@ public final class YangModelBuilderUtil {
                 for (int j = 0; j < childNode.getChildCount(); j++) {
                     ParseTree mandatoryTree = ctx.getChild(j);
                     if (mandatoryTree instanceof Mandatory_argContext) {
-                        Boolean mandatory = Boolean
-                                .valueOf(stringFromNode(mandatoryTree));
+                        Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
                         constraints.setMandatory(mandatory);
                     }
                 }
@@ -1354,8 +1297,7 @@ public final class YangModelBuilderUtil {
             }
             return result;
         } catch (Exception e) {
-            throw new YangParseException(ctx.getStart().getLine(),
-                    "Failed to parse min-elements.", e);
+            throw new YangParseException(ctx.getStart().getLine(), "Failed to parse min-elements.", e);
         }
     }
 
@@ -1373,8 +1315,7 @@ public final class YangModelBuilderUtil {
             }
             return result;
         } catch (Exception e) {
-            throw new YangParseException(ctx.getStart().getLine(),
-                    "Failed to parse max-elements.", e);
+            throw new YangParseException(ctx.getStart().getLine(), "Failed to parse max-elements.", e);
         }
     }
 
@@ -1418,8 +1359,8 @@ public final class YangModelBuilderUtil {
      *             if this is one of YANG type which MUST contain additional
      *             informations in its body
      */
-    public static void checkMissingBody(final String typeName,
-            final String moduleName, final int line) throws YangParseException {
+    public static void checkMissingBody(final String typeName, final String moduleName, final int line)
+            throws YangParseException {
         if ("decimal64".equals(typeName)) {
             throw new YangParseException(moduleName, line,
                     "The 'fraction-digits' statement MUST be present if the type is 'decimal64'.");
@@ -1430,8 +1371,7 @@ public final class YangModelBuilderUtil {
             throw new YangParseException(moduleName, line,
                     "The 'path' statement MUST be present if the type is 'leafref'.");
         } else if ("bits".equals(typeName)) {
-            throw new YangParseException(moduleName, line,
-                    "The 'bit' statement MUST be present if the type is 'bits'.");
+            throw new YangParseException(moduleName, line, "The 'bit' statement MUST be present if the type is 'bits'.");
         } else if ("enumeration".equals(typeName)) {
             throw new YangParseException(moduleName, line,
                     "The 'enum' statement MUST be present if the type is 'enumeration'.");
@@ -1449,8 +1389,7 @@ public final class YangModelBuilderUtil {
      */
     public static RefineHolder parseRefine(Refine_stmtContext refineCtx) {
         final String refineTarget = stringFromNode(refineCtx);
-        final RefineHolder refine = new RefineHolder(refineTarget, refineCtx
-                .getStart().getLine());
+        final RefineHolder refine = new RefineHolder(refineTarget, refineCtx.getStart().getLine());
         for (int j = 0; j < refineCtx.getChildCount(); j++) {
             ParseTree refinePom = refineCtx.getChild(j);
             if (refinePom instanceof Refine_pomContext) {
@@ -1459,23 +1398,17 @@ public final class YangModelBuilderUtil {
                     parseRefineDefault(refine, refineStmt);
 
                     if (refineStmt instanceof Refine_leaf_stmtsContext) {
-                        parseRefine(refine,
-                                (Refine_leaf_stmtsContext) refineStmt);
+                        parseRefine(refine, (Refine_leaf_stmtsContext) refineStmt);
                     } else if (refineStmt instanceof Refine_container_stmtsContext) {
-                        parseRefine(refine,
-                                (Refine_container_stmtsContext) refineStmt);
+                        parseRefine(refine, (Refine_container_stmtsContext) refineStmt);
                     } else if (refineStmt instanceof Refine_list_stmtsContext) {
-                        parseRefine(refine,
-                                (Refine_list_stmtsContext) refineStmt);
+                        parseRefine(refine, (Refine_list_stmtsContext) refineStmt);
                     } else if (refineStmt instanceof Refine_leaf_list_stmtsContext) {
-                        parseRefine(refine,
-                                (Refine_leaf_list_stmtsContext) refineStmt);
+                        parseRefine(refine, (Refine_leaf_list_stmtsContext) refineStmt);
                     } else if (refineStmt instanceof Refine_choice_stmtsContext) {
-                        parseRefine(refine,
-                                (Refine_choice_stmtsContext) refineStmt);
+                        parseRefine(refine, (Refine_choice_stmtsContext) refineStmt);
                     } else if (refineStmt instanceof Refine_anyxml_stmtsContext) {
-                        parseRefine(refine,
-                                (Refine_anyxml_stmtsContext) refineStmt);
+                        parseRefine(refine, (Refine_anyxml_stmtsContext) refineStmt);
                     }
                 }
             }
@@ -1483,8 +1416,7 @@ public final class YangModelBuilderUtil {
         return refine;
     }
 
-    private static void parseRefineDefault(RefineHolder refine,
-            ParseTree refineStmt) {
+    private static void parseRefineDefault(RefineHolder refine, ParseTree refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Description_stmtContext) {
@@ -1500,8 +1432,7 @@ public final class YangModelBuilderUtil {
         }
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine,
-            Refine_leaf_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Default_stmtContext) {
@@ -1511,8 +1442,7 @@ public final class YangModelBuilderUtil {
                 for (int j = 0; j < refineArg.getChildCount(); j++) {
                     ParseTree mandatoryTree = refineArg.getChild(j);
                     if (mandatoryTree instanceof Mandatory_argContext) {
-                        Boolean mandatory = Boolean
-                                .valueOf(stringFromNode(mandatoryTree));
+                        Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
                         refine.setMandatory(mandatory);
                     }
                 }
@@ -1525,8 +1455,7 @@ public final class YangModelBuilderUtil {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine,
-            Refine_container_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(RefineHolder refine, Refine_container_stmtsContext refineStmt) {
         for (int m = 0; m < refineStmt.getChildCount(); m++) {
             ParseTree refineArg = refineStmt.getChild(m);
             if (refineArg instanceof Must_stmtContext) {
@@ -1539,8 +1468,7 @@ public final class YangModelBuilderUtil {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine,
-            Refine_list_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(RefineHolder refine, Refine_list_stmtsContext refineStmt) {
         for (int m = 0; m < refineStmt.getChildCount(); m++) {
             ParseTree refineArg = refineStmt.getChild(m);
             if (refineArg instanceof Must_stmtContext) {
@@ -1557,8 +1485,7 @@ public final class YangModelBuilderUtil {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine,
-            Refine_leaf_list_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_list_stmtsContext refineStmt) {
         for (int m = 0; m < refineStmt.getChildCount(); m++) {
             ParseTree refineArg = refineStmt.getChild(m);
             if (refineArg instanceof Must_stmtContext) {
@@ -1575,8 +1502,7 @@ public final class YangModelBuilderUtil {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine,
-            Refine_choice_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(RefineHolder refine, Refine_choice_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Default_stmtContext) {
@@ -1586,8 +1512,7 @@ public final class YangModelBuilderUtil {
                 for (int j = 0; j < refineArg.getChildCount(); j++) {
                     ParseTree mandatoryTree = refineArg.getChild(j);
                     if (mandatoryTree instanceof Mandatory_argContext) {
-                        Boolean mandatory = Boolean
-                                .valueOf(stringFromNode(mandatoryTree));
+                        Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
                         refine.setMandatory(mandatory);
                     }
                 }
@@ -1596,8 +1521,7 @@ public final class YangModelBuilderUtil {
         return refine;
     }
 
-    private static RefineHolder parseRefine(RefineHolder refine,
-            Refine_anyxml_stmtsContext refineStmt) {
+    private static RefineHolder parseRefine(RefineHolder refine, Refine_anyxml_stmtsContext refineStmt) {
         for (int i = 0; i < refineStmt.getChildCount(); i++) {
             ParseTree refineArg = refineStmt.getChild(i);
             if (refineArg instanceof Must_stmtContext) {
@@ -1607,8 +1531,7 @@ public final class YangModelBuilderUtil {
                 for (int j = 0; j < refineArg.getChildCount(); j++) {
                     ParseTree mandatoryTree = refineArg.getChild(j);
                     if (mandatoryTree instanceof Mandatory_argContext) {
-                        Boolean mandatory = Boolean
-                                .valueOf(stringFromNode(mandatoryTree));
+                        Boolean mandatory = Boolean.valueOf(stringFromNode(mandatoryTree));
                         refine.setMandatory(mandatory);
                     }
                 }
index 35bfb1bebf449290cd97e58eb1af567bc637b35f..3070c74af8c048cce0b0eb3394ea0e837a2d3bba 100644 (file)
@@ -24,12 +24,12 @@ public class YangParserNegativeTest {
     @Test
     public void testInvalidImport() throws IOException {
         try {
-            try (InputStream stream = new FileInputStream(getClass().getResource
-                    ("/negative-scenario/testfile1.yang").getPath())) {
+            try (InputStream stream = new FileInputStream(getClass().getResource("/negative-scenario/testfile1.yang")
+                    .getPath())) {
                 TestUtils.loadModule(stream);
                 fail("ValidationException should by thrown");
             }
-        } catch(YangValidationException e) {
+        } catch (YangValidationException e) {
             assertTrue(e.getMessage().contains("Not existing module imported"));
         }
     }
@@ -37,13 +37,14 @@ public class YangParserNegativeTest {
     @Test
     public void testTypeNotFound() throws IOException {
         try {
-            try (InputStream stream = new FileInputStream(getClass().getResource
-                    ("/negative-scenario/testfile2.yang").getPath())) {
+            try (InputStream stream = new FileInputStream(getClass().getResource("/negative-scenario/testfile2.yang")
+                    .getPath())) {
                 TestUtils.loadModule(stream);
                 fail("YangParseException should by thrown");
             }
-        } catch(YangParseException e) {
-            assertTrue(e.getMessage().contains("Error in module 'test2' on line 24: Referenced type 'int-ext' not found."));
+        } catch (YangParseException e) {
+            assertTrue(e.getMessage().contains(
+                    "Error in module 'test2' on line 24: Referenced type 'int-ext' not found."));
         }
     }
 
@@ -51,19 +52,18 @@ public class YangParserNegativeTest {
     public void testInvalidAugmentTarget() throws IOException {
         try {
             final List<InputStream> streams = new ArrayList<>(2);
-            try (InputStream testFile0 = new FileInputStream(getClass().getResource
-                    ("/negative-scenario/testfile0.yang").getPath())) {
+            try (InputStream testFile0 = new FileInputStream(getClass()
+                    .getResource("/negative-scenario/testfile0.yang").getPath())) {
                 streams.add(testFile0);
-                try (InputStream testFile3 = new FileInputStream(getClass().getResource
-                        ("/negative-scenario/testfile3.yang").getPath())) {
+                try (InputStream testFile3 = new FileInputStream(getClass().getResource(
+                        "/negative-scenario/testfile3.yang").getPath())) {
                     streams.add(testFile3);
-                    assertEquals("Expected loaded files count is 2", 2,
-                            streams.size());
+                    assertEquals("Expected loaded files count is 2", 2, streams.size());
                     TestUtils.loadModules(streams);
                     fail("YangParseException should by thrown");
                 }
             }
-        } catch(YangParseException e) {
+        } catch (YangParseException e) {
             assertTrue(e.getMessage().contains("Failed to resolve augments in module 'test3'."));
         }
     }
@@ -71,14 +71,42 @@ public class YangParserNegativeTest {
     @Test
     public void testInvalidRefine() throws IOException {
         try {
-            try (InputStream stream = new FileInputStream(getClass().getResource
-                    ("/negative-scenario/testfile4.yang").getPath())) {
+            try (InputStream stream = new FileInputStream(getClass().getResource("/negative-scenario/testfile4.yang")
+                    .getPath())) {
                 TestUtils.loadModule(stream);
                 fail("YangParseException should by thrown");
             }
-        } catch(YangParseException e) {
+        } catch (YangParseException e) {
             assertTrue(e.getMessage().contains("Can not refine 'presence' for 'node'."));
         }
     }
 
+    @Test
+    public void testInvalidLength() throws IOException {
+        try {
+            try (InputStream stream = new FileInputStream(getClass().getResource("/negative-scenario/testfile5.yang")
+                    .getPath())) {
+                TestUtils.loadModule(stream);
+                fail("YangParseException should by thrown");
+            }
+        } catch (YangParseException e) {
+            assertTrue(e.getMessage().contains("Invalid length constraint: <4, 10>"));
+        }
+
+    }
+
+    @Test
+    public void testInvalidRange() throws IOException {
+        try {
+            try (InputStream stream = new FileInputStream(getClass().getResource("/negative-scenario/testfile6.yang")
+                    .getPath())) {
+                TestUtils.loadModule(stream);
+                fail("YangParseException should by thrown");
+            }
+        } catch (YangParseException e) {
+            assertTrue(e.getMessage().contains("Invalid range constraint: <5, 20>"));
+        }
+
+    }
+
 }
index ba31e51922a62c2d3fc6b352a2e3aa8110d3d216..9006f93c61bfbd3741c50911bb5f03ff1234e413 100644 (file)
@@ -63,8 +63,7 @@ import org.opendaylight.controller.yang.model.util.Uint32;
 import org.opendaylight.controller.yang.model.util.UnionType;
 
 public class YangParserTest {
-    private final DateFormat simpleDateFormat = new SimpleDateFormat(
-            "yyyy-MM-dd");
+    private final DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 
     private Set<Module> modules;
 
@@ -109,14 +108,12 @@ public class YangParserTest {
         String expectedPrefix = "t2";
         Date expectedRevision = TestUtils.createDate("2013-02-27");
 
-        ContainerSchemaNode interfaces = (ContainerSchemaNode) test
-                .getDataChildByName("interfaces");
+        ContainerSchemaNode interfaces = (ContainerSchemaNode) test.getDataChildByName("interfaces");
         // test SchemaNode args
-        QName expectedQName = new QName(expectedNamespace, expectedRevision,
-                expectedPrefix, "interfaces");
+        QName expectedQName = new QName(expectedNamespace, expectedRevision, expectedPrefix, "interfaces");
         assertEquals(expectedQName, interfaces.getQName());
-        SchemaPath expectedPath = TestUtils.createPath(true, expectedNamespace,
-                expectedRevision, expectedPrefix, "interfaces");
+        SchemaPath expectedPath = TestUtils.createPath(true, expectedNamespace, expectedRevision, expectedPrefix,
+                "interfaces");
         assertEquals(expectedPath, interfaces.getPath());
         assertNull(interfaces.getDescription());
         assertNull(interfaces.getReference());
@@ -141,8 +138,7 @@ public class YangParserTest {
         assertEquals(0, interfaces.getGroupings().size());
         assertEquals(0, interfaces.getUses().size());
 
-        ListSchemaNode ifEntry = (ListSchemaNode) interfaces
-                .getDataChildByName("ifEntry");
+        ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName("ifEntry");
         assertNotNull(ifEntry);
     }
 
@@ -153,17 +149,14 @@ public class YangParserTest {
         String expectedPrefix = "t2";
         Date expectedRevision = TestUtils.createDate("2013-02-27");
 
-        ContainerSchemaNode interfaces = (ContainerSchemaNode) test
-                .getDataChildByName("interfaces");
+        ContainerSchemaNode interfaces = (ContainerSchemaNode) test.getDataChildByName("interfaces");
 
-        ListSchemaNode ifEntry = (ListSchemaNode) interfaces
-                .getDataChildByName("ifEntry");
+        ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName("ifEntry");
         // test SchemaNode args
-        QName expectedQName = new QName(expectedNamespace, expectedRevision,
-                expectedPrefix, "ifEntry");
+        QName expectedQName = new QName(expectedNamespace, expectedRevision, expectedPrefix, "ifEntry");
         assertEquals(expectedQName, ifEntry.getQName());
-        SchemaPath expectedPath = TestUtils.createPath(true, expectedNamespace,
-                expectedRevision, expectedPrefix, "interfaces", "ifEntry");
+        SchemaPath expectedPath = TestUtils.createPath(true, expectedNamespace, expectedRevision, expectedPrefix,
+                "interfaces", "ifEntry");
         assertEquals(expectedPath, ifEntry.getPath());
         assertNull(ifEntry.getDescription());
         assertNull(ifEntry.getReference());
@@ -179,13 +172,11 @@ public class YangParserTest {
         assertEquals(1, (int) constraints.getMinElements());
         assertEquals(11, (int) constraints.getMaxElements());
         // test AugmentationTarget args
-        Set<AugmentationSchema> availableAugmentations = ifEntry
-                .getAvailableAugmentations();
+        Set<AugmentationSchema> availableAugmentations = ifEntry.getAvailableAugmentations();
         assertEquals(2, availableAugmentations.size());
         // test ListSchemaNode args
         List<QName> expectedKey = new ArrayList<QName>();
-        expectedKey.add(new QName(expectedNamespace, expectedRevision,
-                expectedPrefix, "ifIndex"));
+        expectedKey.add(new QName(expectedNamespace, expectedRevision, expectedPrefix, "ifIndex"));
         assertEquals(expectedKey, ifEntry.getKeyDefinition());
         assertFalse(ifEntry.isUserOrdered());
         // test DataNodeContainer args
@@ -194,11 +185,9 @@ public class YangParserTest {
         assertEquals(0, ifEntry.getGroupings().size());
         assertEquals(0, ifEntry.getUses().size());
 
-        LeafSchemaNode ifIndex = (LeafSchemaNode) ifEntry
-                .getDataChildByName("ifIndex");
+        LeafSchemaNode ifIndex = (LeafSchemaNode) ifEntry.getDataChildByName("ifIndex");
         assertTrue(ifIndex.getType() instanceof Uint32);
-        LeafSchemaNode ifMtu = (LeafSchemaNode) ifEntry
-                .getDataChildByName("ifMtu");
+        LeafSchemaNode ifMtu = (LeafSchemaNode) ifEntry.getDataChildByName("ifMtu");
         assertTrue(ifMtu.getType() instanceof Int32);
     }
 
@@ -207,8 +196,7 @@ public class YangParserTest {
         Module test = TestUtils.findModule(modules, "types2");
 
         // leaf if-name
-        LeafSchemaNode ifName = (LeafSchemaNode) test
-                .getDataChildByName("if-name");
+        LeafSchemaNode ifName = (LeafSchemaNode) test.getDataChildByName("if-name");
         Leafref ifNameType = (Leafref) ifName.getType();
         QName qname = ifNameType.getQName();
 
@@ -229,8 +217,7 @@ public class YangParserTest {
         assertEquals("string", nameQName.getLocalName());
 
         // leaf count
-        LeafSchemaNode count = (LeafSchemaNode) test
-                .getDataChildByName("count");
+        LeafSchemaNode count = (LeafSchemaNode) test.getDataChildByName("count");
         ExtendedType countType = (ExtendedType) count.getType();
         QName countTypeQName = countType.getQName();
 
@@ -255,46 +242,40 @@ public class YangParserTest {
         // testfile1
         Module module1 = TestUtils.findModule(modules, "types1");
 
-        Set<AugmentationSchema> module1Augmentations = module1
-                .getAugmentations();
+        Set<AugmentationSchema> module1Augmentations = module1.getAugmentations();
         AugmentationSchema augment1 = module1Augmentations.iterator().next();
-        LeafSchemaNode augmentedLeafDefinition = (LeafSchemaNode) augment1
-                .getDataChildByName("ds0ChannelNumber");
+        LeafSchemaNode augmentedLeafDefinition = (LeafSchemaNode) augment1.getDataChildByName("ds0ChannelNumber");
         assertTrue(augmentedLeafDefinition.isAugmenting());
 
         // testfile2
         Module module2 = TestUtils.findModule(modules, "types2");
 
-        ContainerSchemaNode interfaces = (ContainerSchemaNode) module2
-                .getDataChildByName("interfaces");
-        ListSchemaNode ifEntry = (ListSchemaNode) interfaces
-                .getDataChildByName("ifEntry");
-        ContainerSchemaNode augmentedContainer = (ContainerSchemaNode) ifEntry
-                .getDataChildByName("augment-holder");
+        ContainerSchemaNode interfaces = (ContainerSchemaNode) module2.getDataChildByName("interfaces");
+        ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName("ifEntry");
+        ContainerSchemaNode augmentedContainer = (ContainerSchemaNode) ifEntry.getDataChildByName("augment-holder");
+
+        ContainerSchemaNode schemas = (ContainerSchemaNode) augmentedContainer.getDataChildByName("schemas");
+        LeafSchemaNode linkleaf = (LeafSchemaNode) schemas.getDataChildByName("linkleaf");
+        assertNotNull(linkleaf);
 
         // augmentation defined in testfile1 and augmentation returned from
         // augmented container have to be same
-        Set<AugmentationSchema> augmentedContainerAugments = augmentedContainer
-                .getAvailableAugmentations();
-        AugmentationSchema augmentDefinition = augmentedContainerAugments
-                .iterator().next();
+        Set<AugmentationSchema> augmentedContainerAugments = augmentedContainer.getAvailableAugmentations();
+        AugmentationSchema augmentDefinition = augmentedContainerAugments.iterator().next();
         assertEquals(augment1, augmentDefinition);
 
-        LeafSchemaNode augmentedLeaf = (LeafSchemaNode) augmentedContainer
-                .getDataChildByName("ds0ChannelNumber");
+        LeafSchemaNode augmentedLeaf = (LeafSchemaNode) augmentedContainer.getDataChildByName("ds0ChannelNumber");
         assertTrue(augmentedLeaf.isAugmenting());
         assertEquals(augmentedLeafDefinition, augmentedLeaf);
 
-        Set<AugmentationSchema> ifEntryAugments = ifEntry
-                .getAvailableAugmentations();
+        Set<AugmentationSchema> ifEntryAugments = ifEntry.getAvailableAugmentations();
         assertEquals(2, ifEntryAugments.size());
 
         // testfile3
         Module module3 = TestUtils.findModule(modules, "types3");
 
-        Set<AugmentationSchema> module3Augmentations = module3
-                .getAugmentations();
-        assertEquals(2, module3Augmentations.size());
+        Set<AugmentationSchema> module3Augmentations = module3.getAugmentations();
+        assertEquals(3, module3Augmentations.size());
         AugmentationSchema augment3 = null;
         for (AugmentationSchema as : module3Augmentations) {
             if ("if:ifType='ds0'".equals(as.getWhenCondition().toString())) {
@@ -314,12 +295,9 @@ public class YangParserTest {
     public void testAugmentTarget() {
         Module test = TestUtils.findModule(modules, "types2");
 
-        ContainerSchemaNode interfaces = (ContainerSchemaNode) test
-                .getDataChildByName("interfaces");
-        ListSchemaNode ifEntry = (ListSchemaNode) interfaces
-                .getDataChildByName("ifEntry");
-        Set<AugmentationSchema> augmentations = ifEntry
-                .getAvailableAugmentations();
+        ContainerSchemaNode interfaces = (ContainerSchemaNode) test.getDataChildByName("interfaces");
+        ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName("ifEntry");
+        Set<AugmentationSchema> augmentations = ifEntry.getAvailableAugmentations();
         assertEquals(2, augmentations.size());
 
         AugmentationSchema augment = null;
@@ -328,29 +306,25 @@ public class YangParserTest {
                 augment = as;
             }
         }
-        ContainerSchemaNode augmentHolder = (ContainerSchemaNode) augment
-                .getDataChildByName("augment-holder");
+        ContainerSchemaNode augmentHolder = (ContainerSchemaNode) augment.getDataChildByName("augment-holder");
         assertNotNull(augmentHolder);
         assertTrue(augmentHolder.isAugmenting());
         QName augmentHolderQName = augmentHolder.getQName();
         assertEquals("augment-holder", augmentHolderQName.getLocalName());
         assertEquals("t3", augmentHolderQName.getPrefix());
-        assertEquals("Description for augment holder",
-                augmentHolder.getDescription());
+        assertEquals("Description for augment holder", augmentHolder.getDescription());
     }
 
     @Test
     public void testTypedefRangesResolving() throws ParseException {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("testleaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("testleaf");
         ExtendedType leafType = (ExtendedType) testleaf.getType();
         QName leafTypeQName = leafType.getQName();
         assertEquals("my-type1", leafTypeQName.getLocalName());
         assertEquals("t1", leafTypeQName.getPrefix());
-        assertEquals(URI.create("urn:simple.container.demo"),
-                leafTypeQName.getNamespace());
+        assertEquals(URI.create("urn:simple.container.demo"), leafTypeQName.getNamespace());
         Date expectedDate = simpleDateFormat.parse("2013-02-27");
         assertEquals(expectedDate, leafTypeQName.getRevision());
         assertEquals(1, leafType.getRanges().size());
@@ -359,15 +333,14 @@ public class YangParserTest {
         QName baseTypeQName = baseType.getQName();
         assertEquals("my-type1", baseTypeQName.getLocalName());
         assertEquals("t2", baseTypeQName.getPrefix());
-        assertEquals(URI.create("urn:simple.types.data.demo"),
-                baseTypeQName.getNamespace());
+        assertEquals(URI.create("urn:simple.types.data.demo"), baseTypeQName.getNamespace());
         assertEquals(expectedDate, baseTypeQName.getRevision());
         assertEquals(2, baseType.getRanges().size());
 
         List<RangeConstraint> ranges = leafType.getRanges();
         assertEquals(1, ranges.size());
         RangeConstraint range = ranges.get(0);
-        assertEquals(3L, range.getMin());
+        assertEquals(12L, range.getMin());
         assertEquals(20L, range.getMax());
     }
 
@@ -375,8 +348,7 @@ public class YangParserTest {
     public void testTypedefPatternsResolving() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("test-string-leaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("test-string-leaf");
         ExtendedType testleafType = (ExtendedType) testleaf.getType();
         QName testleafTypeQName = testleafType.getQName();
         assertEquals("my-string-type-ext", testleafTypeQName.getLocalName());
@@ -403,8 +375,7 @@ public class YangParserTest {
     public void testTypedefLengthsResolving() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("leaf-with-length");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("leaf-with-length");
         ExtendedType testleafType = (ExtendedType) testleaf.getType();
         assertEquals("my-string-type", testleafType.getQName().getLocalName());
 
@@ -420,8 +391,7 @@ public class YangParserTest {
     public void testTypeDef() {
         Module testModule = TestUtils.findModule(modules, "types2");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("nested-type-leaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("nested-type-leaf");
         ExtendedType testleafType = (ExtendedType) testleaf.getType();
         assertEquals("my-type1", testleafType.getQName().getLocalName());
 
@@ -430,8 +400,7 @@ public class YangParserTest {
 
         Int32 int32Type = (Int32) baseType.getBaseType();
         QName qname = int32Type.getQName();
-        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"),
-                qname.getNamespace());
+        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"), qname.getNamespace());
         assertNull(qname.getRevision());
         assertEquals("", qname.getPrefix());
         assertEquals("int32", qname.getLocalName());
@@ -446,8 +415,7 @@ public class YangParserTest {
     public void testTypedefDecimal1() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("test-decimal-leaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("test-decimal-leaf");
         ExtendedType type = (ExtendedType) testleaf.getType();
         assertEquals(4, (int) type.getFractionDigits());
 
@@ -463,8 +431,7 @@ public class YangParserTest {
     public void testTypedefDecimal2() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("test-decimal-leaf2");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("test-decimal-leaf2");
         TypeDefinition<?> baseType = testleaf.getType().getBaseType();
         assertTrue(testleaf.getType().getBaseType() instanceof Decimal64);
         Decimal64 baseTypeCast = (Decimal64) baseType;
@@ -475,8 +442,7 @@ public class YangParserTest {
     public void testTypedefUnion() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("union-leaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("union-leaf");
         ExtendedType testleafType = (ExtendedType) testleaf.getType();
         assertEquals("my-union-ext", testleafType.getQName().getLocalName());
 
@@ -501,8 +467,7 @@ public class YangParserTest {
     public void testNestedUnionResolving1() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("nested-union-leaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("nested-union-leaf");
 
         ExtendedType nestedUnion1 = (ExtendedType) testleaf.getType();
         assertEquals("nested-union1", nestedUnion1.getQName().getLocalName());
@@ -517,14 +482,11 @@ public class YangParserTest {
         assertTrue(unionTypes.get(1) instanceof ExtendedType);
 
         ExtendedType extendedUnion = (ExtendedType) unionTypes.get(1);
-        ExtendedType extendedUnionBase = (ExtendedType) extendedUnion
-                .getBaseType();
+        ExtendedType extendedUnionBase = (ExtendedType) extendedUnion.getBaseType();
         assertEquals("my-union", extendedUnionBase.getQName().getLocalName());
 
-        UnionType extendedTargetUnion = (UnionType) extendedUnionBase
-                .getBaseType();
-        List<TypeDefinition<?>> extendedTargetTypes = extendedTargetUnion
-                .getTypes();
+        UnionType extendedTargetUnion = (UnionType) extendedUnionBase.getBaseType();
+        List<TypeDefinition<?>> extendedTargetTypes = extendedTargetUnion.getTypes();
         assertTrue(extendedTargetTypes.get(0).getBaseType() instanceof Int16);
         assertTrue(extendedTargetTypes.get(1) instanceof Int32);
 
@@ -541,24 +503,19 @@ public class YangParserTest {
     public void testNestedUnionResolving2() {
         Module testModule = TestUtils.findModule(modules, "types1");
 
-        LeafSchemaNode testleaf = (LeafSchemaNode) testModule
-                .getDataChildByName("custom-union-leaf");
+        LeafSchemaNode testleaf = (LeafSchemaNode) testModule.getDataChildByName("custom-union-leaf");
 
         ExtendedType testleafType = (ExtendedType) testleaf.getType();
         QName testleafTypeQName = testleafType.getQName();
-        assertEquals(URI.create("urn:simple.container.demo.test"),
-                testleafTypeQName.getNamespace());
-        assertEquals(TestUtils.createDate("2013-02-27"),
-                testleafTypeQName.getRevision());
+        assertEquals(URI.create("urn:simple.container.demo.test"), testleafTypeQName.getNamespace());
+        assertEquals(TestUtils.createDate("2013-02-27"), testleafTypeQName.getRevision());
         assertEquals("t3", testleafTypeQName.getPrefix());
         assertEquals("union1", testleafTypeQName.getLocalName());
 
         ExtendedType union2 = (ExtendedType) testleafType.getBaseType();
         QName union2QName = union2.getQName();
-        assertEquals(URI.create("urn:simple.container.demo.test"),
-                union2QName.getNamespace());
-        assertEquals(TestUtils.createDate("2013-02-27"),
-                union2QName.getRevision());
+        assertEquals(URI.create("urn:simple.container.demo.test"), union2QName.getNamespace());
+        assertEquals(TestUtils.createDate("2013-02-27"), union2QName.getRevision());
         assertEquals("t3", union2QName.getPrefix());
         assertEquals("union2", union2QName.getLocalName());
 
@@ -570,10 +527,8 @@ public class YangParserTest {
 
         ExtendedType nestedUnion2 = (ExtendedType) unionTypes.get(1);
         QName nestedUnion2QName = nestedUnion2.getQName();
-        assertEquals(URI.create("urn:simple.types.data.demo"),
-                nestedUnion2QName.getNamespace());
-        assertEquals(TestUtils.createDate("2013-02-27"),
-                nestedUnion2QName.getRevision());
+        assertEquals(URI.create("urn:simple.types.data.demo"), nestedUnion2QName.getNamespace());
+        assertEquals(TestUtils.createDate("2013-02-27"), nestedUnion2QName.getRevision());
         assertEquals("t2", nestedUnion2QName.getPrefix());
         assertEquals("nested-union2", nestedUnion2QName.getLocalName());
 
@@ -585,19 +540,15 @@ public class YangParserTest {
 
         ExtendedType myUnionExt = (ExtendedType) nestedUnion2Types.get(1);
         QName myUnionExtQName = myUnionExt.getQName();
-        assertEquals(URI.create("urn:simple.types.data.demo"),
-                myUnionExtQName.getNamespace());
-        assertEquals(TestUtils.createDate("2013-02-27"),
-                myUnionExtQName.getRevision());
+        assertEquals(URI.create("urn:simple.types.data.demo"), myUnionExtQName.getNamespace());
+        assertEquals(TestUtils.createDate("2013-02-27"), myUnionExtQName.getRevision());
         assertEquals("t2", myUnionExtQName.getPrefix());
         assertEquals("my-union-ext", myUnionExtQName.getLocalName());
 
         ExtendedType myUnion = (ExtendedType) myUnionExt.getBaseType();
         QName myUnionQName = myUnion.getQName();
-        assertEquals(URI.create("urn:simple.types.data.demo"),
-                myUnionQName.getNamespace());
-        assertEquals(TestUtils.createDate("2013-02-27"),
-                myUnionQName.getRevision());
+        assertEquals(URI.create("urn:simple.types.data.demo"), myUnionQName.getNamespace());
+        assertEquals(TestUtils.createDate("2013-02-27"), myUnionQName.getRevision());
         assertEquals("t2", myUnionQName.getPrefix());
         assertEquals("my-union", myUnionQName.getLocalName());
 
@@ -618,10 +569,8 @@ public class YangParserTest {
     public void testRefine() {
         Module testModule = TestUtils.findModule(modules, "types2");
 
-        ContainerSchemaNode peer = (ContainerSchemaNode) testModule
-                .getDataChildByName("peer");
-        ContainerSchemaNode destination = (ContainerSchemaNode) peer
-                .getDataChildByName("destination");
+        ContainerSchemaNode peer = (ContainerSchemaNode) testModule.getDataChildByName("peer");
+        ContainerSchemaNode destination = (ContainerSchemaNode) peer.getDataChildByName("destination");
         Set<UsesNode> usesNodes = destination.getUses();
         assertEquals(1, usesNodes.size());
         UsesNode usesNode = usesNodes.iterator().next();
@@ -651,53 +600,39 @@ public class YangParserTest {
         // leaf address
         assertNotNull(refineLeaf);
         assertEquals("address", refineLeaf.getQName().getLocalName());
-        assertEquals("description of address defined by refine",
-                refineLeaf.getDescription());
-        assertEquals("address reference added by refine",
-                refineLeaf.getReference());
+        assertEquals("description of address defined by refine", refineLeaf.getDescription());
+        assertEquals("address reference added by refine", refineLeaf.getReference());
         assertFalse(refineLeaf.isConfiguration());
         assertTrue(refineLeaf.getConstraints().isMandatory());
-        Set<MustDefinition> leafMustConstraints = refineLeaf.getConstraints()
-                .getMustConstraints();
+        Set<MustDefinition> leafMustConstraints = refineLeaf.getConstraints().getMustConstraints();
         assertEquals(1, leafMustConstraints.size());
         MustDefinition leafMust = leafMustConstraints.iterator().next();
-        assertEquals(
-                "\"ifType != 'ethernet' or (ifType = 'ethernet' and ifMTU = 1500)\"",
-                leafMust.toString());
+        assertEquals("\"ifType != 'ethernet' or (ifType = 'ethernet' and ifMTU = 1500)\"", leafMust.toString());
 
         // container port
         assertNotNull(refineContainer);
-        Set<MustDefinition> mustConstraints = refineContainer.getConstraints()
-                .getMustConstraints();
+        Set<MustDefinition> mustConstraints = refineContainer.getConstraints().getMustConstraints();
         assertTrue(mustConstraints.isEmpty());
-        assertEquals("description of port defined by refine",
-                refineContainer.getDescription());
-        assertEquals("port reference added by refine",
-                refineContainer.getReference());
+        assertEquals("description of port defined by refine", refineContainer.getDescription());
+        assertEquals("port reference added by refine", refineContainer.getReference());
         assertFalse(refineContainer.isConfiguration());
         assertTrue(refineContainer.isPresenceContainer());
 
         // list addresses
         assertNotNull(refineList);
-        assertEquals("description of addresses defined by refine",
-                refineList.getDescription());
-        assertEquals("addresses reference added by refine",
-                refineList.getReference());
+        assertEquals("description of addresses defined by refine", refineList.getDescription());
+        assertEquals("addresses reference added by refine", refineList.getReference());
         assertFalse(refineList.isConfiguration());
         assertEquals(2, (int) refineList.getConstraints().getMinElements());
         assertEquals(12, (int) refineList.getConstraints().getMaxElements());
 
         // grouping target-inner
         assertNotNull(refineGrouping);
-        Set<DataSchemaNode> refineGroupingChildren = refineGrouping
-                .getChildNodes();
+        Set<DataSchemaNode> refineGroupingChildren = refineGrouping.getChildNodes();
         assertEquals(1, refineGroupingChildren.size());
-        LeafSchemaNode refineGroupingLeaf = (LeafSchemaNode) refineGroupingChildren
-                .iterator().next();
-        assertEquals("inner-grouping-id", refineGroupingLeaf.getQName()
-                .getLocalName());
-        assertEquals("new target-inner grouping description",
-                refineGrouping.getDescription());
+        LeafSchemaNode refineGroupingLeaf = (LeafSchemaNode) refineGroupingChildren.iterator().next();
+        assertEquals("inner-grouping-id", refineGroupingLeaf.getQName().getLocalName());
+        assertEquals("new target-inner grouping description", refineGrouping.getDescription());
 
         // typedef group-type
         assertNotNull(typedef);
@@ -709,8 +644,7 @@ public class YangParserTest {
     @Test
     public void testChoice() {
         Module testModule = TestUtils.findModule(modules, "types1");
-        ContainerSchemaNode peer = (ContainerSchemaNode) testModule
-                .getDataChildByName("transfer");
+        ContainerSchemaNode peer = (ContainerSchemaNode) testModule.getDataChildByName("transfer");
         ChoiceNode how = (ChoiceNode) peer.getDataChildByName("how");
         Set<ChoiceCaseNode> cases = how.getCases();
         assertEquals(3, cases.size());
@@ -719,8 +653,7 @@ public class YangParserTest {
     @Test
     public void testAnyXml() {
         Module testModule = TestUtils.findModule(modules, "types1");
-        AnyXmlSchemaNode data = (AnyXmlSchemaNode) testModule
-                .getDataChildByName("data");
+        AnyXmlSchemaNode data = (AnyXmlSchemaNode) testModule.getDataChildByName("data");
         assertNotNull(data);
     }
 
@@ -731,8 +664,7 @@ public class YangParserTest {
         assertEquals(1, deviations.size());
 
         Deviation dev = deviations.iterator().next();
-        SchemaPath expectedPath = TestUtils.createPath(true, null, null,
-                "data", "system", "user");
+        SchemaPath expectedPath = TestUtils.createPath(true, null, null, "data", "system", "user");
         assertEquals(expectedPath, dev.getTargetPath());
         assertEquals(Deviate.ADD, dev.getDeviate());
     }
@@ -740,8 +672,7 @@ public class YangParserTest {
     @Test
     public void testUnknownNode() {
         Module testModule = TestUtils.findModule(modules, "types3");
-        ContainerSchemaNode network = (ContainerSchemaNode) testModule
-                .getDataChildByName("network");
+        ContainerSchemaNode network = (ContainerSchemaNode) testModule.getDataChildByName("network");
         List<UnknownSchemaNode> unknownNodes = network.getUnknownSchemaNodes();
         assertEquals(1, unknownNodes.size());
         UnknownSchemaNode unknownNode = unknownNodes.get(0);
@@ -759,8 +690,7 @@ public class YangParserTest {
     @Test
     public void testExtension() {
         Module testModule = TestUtils.findModule(modules, "types3");
-        List<ExtensionDefinition> extensions = testModule
-                .getExtensionSchemaNodes();
+        List<ExtensionDefinition> extensions = testModule.getExtensionSchemaNodes();
         assertEquals(1, extensions.size());
         ExtensionDefinition extension = extensions.get(0);
         assertEquals("name", extension.getArgument());
@@ -774,17 +704,15 @@ public class YangParserTest {
         String expectedPrefix = "t3";
         Date expectedRevision = TestUtils.createDate("2013-02-27");
 
-        Set<NotificationDefinition> notifications = testModule
-                .getNotifications();
+        Set<NotificationDefinition> notifications = testModule.getNotifications();
         assertEquals(1, notifications.size());
 
         NotificationDefinition notification = notifications.iterator().next();
         // test SchemaNode args
-        QName expectedQName = new QName(expectedNamespace, expectedRevision,
-                expectedPrefix, "event");
+        QName expectedQName = new QName(expectedNamespace, expectedRevision, expectedPrefix, "event");
         assertEquals(expectedQName, notification.getQName());
-        SchemaPath expectedPath = TestUtils.createPath(true, expectedNamespace,
-                expectedRevision, expectedPrefix, "event");
+        SchemaPath expectedPath = TestUtils.createPath(true, expectedNamespace, expectedRevision, expectedPrefix,
+                "event");
         assertEquals(expectedPath, notification.getPath());
         assertNull(notification.getDescription());
         assertNull(notification.getReference());
@@ -796,14 +724,11 @@ public class YangParserTest {
         assertEquals(0, notification.getGroupings().size());
         assertEquals(0, notification.getUses().size());
 
-        LeafSchemaNode eventClass = (LeafSchemaNode) notification
-                .getDataChildByName("event-class");
+        LeafSchemaNode eventClass = (LeafSchemaNode) notification.getDataChildByName("event-class");
         assertTrue(eventClass.getType() instanceof StringType);
-        AnyXmlSchemaNode reportingEntity = (AnyXmlSchemaNode) notification
-                .getDataChildByName("reporting-entity");
+        AnyXmlSchemaNode reportingEntity = (AnyXmlSchemaNode) notification.getDataChildByName("reporting-entity");
         assertNotNull(reportingEntity);
-        LeafSchemaNode severity = (LeafSchemaNode) notification
-                .getDataChildByName("severity");
+        LeafSchemaNode severity = (LeafSchemaNode) notification.getDataChildByName("severity");
         assertTrue(severity.getType() instanceof StringType);
     }
 
@@ -815,8 +740,7 @@ public class YangParserTest {
         assertEquals(1, rpcs.size());
 
         RpcDefinition rpc = rpcs.iterator().next();
-        assertEquals("Retrieve all or part of a specified configuration.",
-                rpc.getDescription());
+        assertEquals("Retrieve all or part of a specified configuration.", rpc.getDescription());
         assertEquals("RFC 6241, Section 7.1", rpc.getReference());
 
         ContainerSchemaNode input = rpc.getInput();
@@ -843,49 +767,41 @@ public class YangParserTest {
         assertEquals(1, augments.size());
         AugmentationSchema augment = augments.iterator().next();
 
-        LeafSchemaNode ifcId = (LeafSchemaNode) augment
-                .getDataChildByName("interface-id");
+        LeafSchemaNode ifcId = (LeafSchemaNode) augment.getDataChildByName("interface-id");
         Leafref ifcIdType = (Leafref) ifcId.getType();
         SchemaPath ifcIdTypeSchemaPath = ifcIdType.getPath();
         List<QName> ifcIdTypePath = ifcIdTypeSchemaPath.getPath();
-        
+
         URI types1URI = URI.create("urn:simple.container.demo");
         URI types2URI = URI.create("urn:simple.types.data.demo");
         URI types3URI = URI.create("urn:simple.container.demo.test");
         Date expectedDate = simpleDateFormat.parse("2013-02-27");
-        
-        QName q0 = new QName(types2URI,
-                expectedDate, "data", "interfaces");
-        QName q1 = new QName(types2URI,
-                expectedDate, "data", "ifEntry");
-        QName q2 = new QName(types3URI,
-                expectedDate, "data", "augment-holder");
-        QName q3 = new QName(types1URI,
-                expectedDate, "data", "interface-id");
+
+        QName q0 = new QName(types2URI, expectedDate, "data", "interfaces");
+        QName q1 = new QName(types2URI, expectedDate, "data", "ifEntry");
+        QName q2 = new QName(types3URI, expectedDate, "data", "augment-holder");
+        QName q3 = new QName(types1URI, expectedDate, "data", "interface-id");
         assertEquals(q0, ifcIdTypePath.get(0));
         assertEquals(q1, ifcIdTypePath.get(1));
         assertEquals(q2, ifcIdTypePath.get(2));
         assertEquals(q3, ifcIdTypePath.get(3));
 
-        LeafListSchemaNode higherLayer = (LeafListSchemaNode) augment
-                .getDataChildByName("higher-layer-if");
+        LeafListSchemaNode higherLayer = (LeafListSchemaNode) augment.getDataChildByName("higher-layer-if");
         Leafref higherLayerType = (Leafref) higherLayer.getType();
         SchemaPath higherLayerTypeSchemaPath = higherLayerType.getPath();
         List<QName> higherLayerTypePath = higherLayerTypeSchemaPath.getPath();
         assertEquals(q0, higherLayerTypePath.get(0));
         assertEquals(q1, higherLayerTypePath.get(1));
         assertEquals(q2, higherLayerTypePath.get(2));
-        q3 = new QName(types1URI,
-                expectedDate, "data", "higher-layer-if");
+        q3 = new QName(types1URI, expectedDate, "data", "higher-layer-if");
         assertEquals(q3, higherLayerTypePath.get(3));
-        
-        LeafSchemaNode myType = (LeafSchemaNode) augment
-                .getDataChildByName("my-type");
-        ExtendedType leafType = (ExtendedType)myType.getType();
-        
+
+        LeafSchemaNode myType = (LeafSchemaNode) augment.getDataChildByName("my-type");
+        ExtendedType leafType = (ExtendedType) myType.getType();
+
         testModule = TestUtils.findModule(modules, "types2");
         TypeDefinition<?> typedef = TestUtils.findTypedef(testModule.getTypeDefinitions(), "my-type1");
-        
+
         assertEquals(typedef, leafType);
     }
 
@@ -895,8 +811,7 @@ public class YangParserTest {
         Set<TypeDefinition<?>> types = test.getTypeDefinitions();
 
         // my-base-int32-type
-        ExtendedType int32Typedef = (ExtendedType) TestUtils.findTypedef(types,
-                "my-base-int32-type");
+        ExtendedType int32Typedef = (ExtendedType) TestUtils.findTypedef(types, "my-base-int32-type");
         QName int32TypedefQName = int32Typedef.getQName();
 
         URI expectedNS = URI.create("urn:simple.types.data.demo");
@@ -914,8 +829,7 @@ public class YangParserTest {
         // my-base-int32-type/int32
         Int32 int32 = (Int32) int32Typedef.getBaseType();
         QName int32QName = int32.getQName();
-        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"),
-                int32QName.getNamespace());
+        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"), int32QName.getNamespace());
         assertNull(int32QName.getRevision());
         assertEquals("", int32QName.getPrefix());
         assertEquals("int32", int32QName.getLocalName());
@@ -933,8 +847,7 @@ public class YangParserTest {
         Set<TypeDefinition<?>> types = test.getTypeDefinitions();
 
         // my-base-int32-type
-        ExtendedType myDecType = (ExtendedType) TestUtils.findTypedef(types,
-                "my-decimal-type");
+        ExtendedType myDecType = (ExtendedType) TestUtils.findTypedef(types, "my-decimal-type");
         QName myDecTypeQName = myDecType.getQName();
 
         URI expectedNS = URI.create("urn:simple.types.data.demo");
@@ -953,8 +866,7 @@ public class YangParserTest {
         Decimal64 dec64 = (Decimal64) myDecType.getBaseType();
         QName dec64QName = dec64.getQName();
 
-        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"),
-                dec64QName.getNamespace());
+        assertEquals(URI.create("urn:ietf:params:xml:ns:yang:1"), dec64QName.getNamespace());
         assertNull(dec64QName.getRevision());
         assertEquals("", dec64QName.getPrefix());
         assertEquals("decimal64", dec64QName.getLocalName());
index 3dbfa780a3527641933e1dae3e77c237822bbe47..f6bc34d1b609eea9c9616d7f3e2585a0b757a098 100644 (file)
@@ -22,7 +22,7 @@ module types1 {
 
     leaf testleaf {
         type data:my-type1 {
-            range "min..max";
+            range "12..max";
         }
     }
 
@@ -126,6 +126,8 @@ module types1 {
         leaf my-type {
             type data:my-type1;
         }
+        container schemas {
+        }
     }
     
     container mycont {
index 904c8e66fd2c3d8dd8ad9dc2f32588604ffc867f..e594749508eade661824f002191d1287fd1c2ba8 100644 (file)
@@ -35,7 +35,7 @@ module types2 {
     
     typedef my-string-type {
         type my-custom-string {
-            length "5..10";
+            length "6..10";
         }
     }
     
index 7aadc9a54fa36451f9b360ede8669e6a41cfa014..495653c96a744aa95442a9c154aeaba15c31e406 100644 (file)
@@ -39,6 +39,13 @@ module types3 {
             description "Description for augment holder";
         }
     }
+    
+    augment "/data:interfaces/data:ifEntry/t3:augment-holder/t1:schemas" {
+        when "if:leafType='ds1'";
+        leaf linkleaf {
+            type binary;
+        }
+    }
 
     container network {
         mnt:mountpoint point {
diff --git a/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/testfile5.yang b/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/testfile5.yang
new file mode 100644 (file)
index 0000000..0d8de38
--- /dev/null
@@ -0,0 +1,19 @@
+module test5 {
+    yang-version 1;
+    namespace "urn:simple.container.demo";
+    prefix "t1";
+
+    typedef my-custom-string {
+        type string {
+            pattern "[a-k]*";
+            length "5..11";
+        }
+    }
+
+    typedef my-string-type {
+        type my-custom-string {
+            length "4..10";
+        }
+    }
+
+}
diff --git a/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/testfile6.yang b/opendaylight/sal/yang-prototype/code-generator/yang-model-parser-impl/src/test/resources/negative-scenario/testfile6.yang
new file mode 100644 (file)
index 0000000..31a4c1e
--- /dev/null
@@ -0,0 +1,18 @@
+module test5 {
+    yang-version 1;
+    namespace "urn:simple.container.demo";
+    prefix "t1";
+
+    typedef my-custom-int {
+        type int32 {
+            range "5..11 | 15..20";
+        }
+    }
+
+    typedef my-int-type {
+        type my-custom-int {
+            range "min..max";
+        }
+    }
+
+}
index b67da660cc0dcca222d7d44ddc380fc091fbbb0d..03a8962d552c26031e51f178e0160c30a77e8d8f 100644 (file)
@@ -19,5 +19,7 @@ public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
      * @return ChoiceCaseNode objects defined in this node
      */
     Set<ChoiceCaseNode> getCases();
+    
+    String getDefaultCase();
 
 }
index 6d5b5be8a0378dfa27fee06687e6174c860a1078..79b211f263e3fc40415463eb48a9743185d2eba5 100644 (file)
@@ -19,7 +19,7 @@ import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefini
  * interface which represents UNSIGNED Integer values defined in Yang language. <br>
  * The integer built-in types in Yang are uint8, uint16, uint32, and uint64.
  * They represent unsigned integers of different sizes:
- *
+ * 
  * <ul>
  * <li>uint8 - represents integer values between 0 and 255, inclusively.</li>
  * <li>uint16 - represents integer values between 0 and 65535, inclusively.</li>
@@ -28,10 +28,10 @@ import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefini
  * <li>uint64 - represents integer values between 0 and 18446744073709551615,
  * inclusively.</li>
  * </ul>
- *
+ * 
  */
-public abstract class AbstractUnsignedInteger implements
-        UnsignedIntegerTypeDefinition {
+public abstract class AbstractUnsignedInteger implements UnsignedIntegerTypeDefinition {
+    private static final long MIN_VALUE = 0;
     private final QName name;
     private final SchemaPath path;
     private final String description;
@@ -40,28 +40,25 @@ public abstract class AbstractUnsignedInteger implements
     private final List<RangeConstraint> rangeStatements;
 
     /**
-     *
+     * 
      * @param actualPath
      * @param namespace
      * @param revision
      * @param name
      * @param description
-     * @param minRange
+     * @param MIN_VALUE
      * @param maxRange
      * @param units
      */
-    public AbstractUnsignedInteger(final SchemaPath path, final QName name,
-            final String description, final Number minRange,
+    public AbstractUnsignedInteger(final SchemaPath path, final QName name, final String description,
             final Number maxRange, final String units) {
         this.name = name;
         this.description = description;
         this.path = path;
         this.units = units;
         this.rangeStatements = new ArrayList<RangeConstraint>();
-        final String rangeDescription = "Integer values between " + minRange
-                + " and " + maxRange + ", inclusively.";
-        this.rangeStatements.add(BaseConstraints.rangeConstraint(minRange,
-                maxRange, rangeDescription,
+        final String rangeDescription = "Integer values between " + MIN_VALUE + " and " + maxRange + ", inclusively.";
+        this.rangeStatements.add(BaseConstraints.rangeConstraint(MIN_VALUE, maxRange, rangeDescription,
                 "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
     }
 
@@ -71,8 +68,7 @@ public abstract class AbstractUnsignedInteger implements
      * @param rangeStatements
      * @param units
      */
-    public AbstractUnsignedInteger(final SchemaPath path, final QName name,
-            final String description,
+    public AbstractUnsignedInteger(final SchemaPath path, final QName name, final String description,
             final List<RangeConstraint> rangeStatements, final String units) {
         this.name = name;
         this.description = description;
@@ -125,14 +121,11 @@ public abstract class AbstractUnsignedInteger implements
     public int hashCode() {
         final int prime = 31;
         int result = 1;
-        result = prime * result
-                + ((description == null) ? 0 : description.hashCode());
+        result = prime * result + ((description == null) ? 0 : description.hashCode());
         result = prime * result + ((name == null) ? 0 : name.hashCode());
         result = prime * result + ((path == null) ? 0 : path.hashCode());
-        result = prime * result
-                + ((rangeStatements == null) ? 0 : rangeStatements.hashCode());
-        result = prime * result
-                + ((reference == null) ? 0 : reference.hashCode());
+        result = prime * result + ((rangeStatements == null) ? 0 : rangeStatements.hashCode());
+        result = prime * result + ((reference == null) ? 0 : reference.hashCode());
         result = prime * result + ((units == null) ? 0 : units.hashCode());
         return result;
     }
index 79ae4674b0b48971005c09ad76cad8d528b6a215..6cae33b8f5ae67614f6479b032de10a949f70ead 100644 (file)
@@ -18,13 +18,14 @@ import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefini
  *
  */
 public final class Uint16 extends AbstractUnsignedInteger {
+    public static final int MAX_VALUE = 65535;
     private static final QName name = BaseTypes.constructQName("uint16");
     private Integer defaultValue = null;
     private static final String description = "uint16 represents integer values between 0 and 65535, inclusively.";
     private final UnsignedIntegerTypeDefinition baseType;
 
     public Uint16(final SchemaPath path) {
-        super(path, name, description, Short.MIN_VALUE, Short.MAX_VALUE, "");
+        super(path, name, description, MAX_VALUE, "");
         this.baseType = this;
     }
 
@@ -55,8 +56,7 @@ public final class Uint16 extends AbstractUnsignedInteger {
     public int hashCode() {
         final int prime = 31;
         int result = super.hashCode();
-        result = prime * result
-                + ((defaultValue == null) ? 0 : defaultValue.hashCode());
+        result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
         return result;
     }
 
@@ -92,4 +92,5 @@ public final class Uint16 extends AbstractUnsignedInteger {
         builder.append("]");
         return builder.toString();
     }
+
 }
index fddf0c4008f9c172486a891f49012ef466412a1b..2a06a603e88c0a559a4d90a0470a282831d83005 100644 (file)
@@ -13,18 +13,18 @@ import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefini
 
 /**
  * Implementation of Yang uint32 built-in type. <br>
- * uint32 represents integer values between 0 and 4294967295, inclusively. The
- * Java counterpart of Yang uint32 built-in type is {@link Long}.
+ * uint32 represents integer values between 0 and 4294967295, inclusively.
  *
  */
 public final class Uint32 extends AbstractUnsignedInteger {
+    public static final long MAX_VALUE = 4294967295L;
     private static final QName name = BaseTypes.constructQName("uint32");
     private final Long defaultValue = null;
     private static final String description = "uint32 represents integer values between 0 and 4294967295, inclusively.";
     private final UnsignedIntegerTypeDefinition baseType;
 
     public Uint32(final SchemaPath path) {
-        super(path, name, description, Short.MIN_VALUE, Short.MAX_VALUE, "");
+        super(path, name, description, MAX_VALUE, "");
         this.baseType = this;
     }
 
@@ -55,8 +55,7 @@ public final class Uint32 extends AbstractUnsignedInteger {
     public int hashCode() {
         final int prime = 31;
         int result = super.hashCode();
-        result = prime * result
-                + ((defaultValue == null) ? 0 : defaultValue.hashCode());
+        result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
         return result;
     }
 
@@ -92,4 +91,5 @@ public final class Uint32 extends AbstractUnsignedInteger {
         builder.append("]");
         return builder.toString();
     }
+
 }
index 9252c08f577715c6744201d1a1b507373ff6f9e8..e95a6232dbb0102e48db2a9e721c106bc87fe98a 100644 (file)
@@ -21,13 +21,14 @@ import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefini
  *
  */
 public final class Uint64 extends AbstractUnsignedInteger {
+    public static final BigInteger MAX_VALUE = new BigInteger("18446744073709551615");
     private static final QName name = BaseTypes.constructQName("uint64");
     private final BigInteger defaultValue = null;
     private static final String description = "uint64 represents integer values between 0 and 18446744073709551615, inclusively.";
     private final UnsignedIntegerTypeDefinition baseType;
 
     public Uint64(final SchemaPath path) {
-        super(path, name, description, Short.MIN_VALUE, Short.MAX_VALUE, "");
+        super(path, name, description, MAX_VALUE, "");
         this.baseType = this;
     }
 
@@ -58,8 +59,7 @@ public final class Uint64 extends AbstractUnsignedInteger {
     public int hashCode() {
         final int prime = 31;
         int result = super.hashCode();
-        result = prime * result
-                + ((defaultValue == null) ? 0 : defaultValue.hashCode());
+        result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
         return result;
     }
 
@@ -95,4 +95,5 @@ public final class Uint64 extends AbstractUnsignedInteger {
         builder.append("]");
         return builder.toString();
     }
+
 }
index fa9d35ea291b2635aab13dc8f420df9dde1a4b86..85e7aab15553104d3d79674e1389ea19381ade75 100644 (file)
@@ -1,10 +1,10 @@
 /*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.yang.model.util;
 
 import org.opendaylight.controller.yang.common.QName;
@@ -12,30 +12,28 @@ import org.opendaylight.controller.yang.model.api.SchemaPath;
 import org.opendaylight.controller.yang.model.api.type.UnsignedIntegerTypeDefinition;
 
 /**
- * Implementation of Yang uint8 built-in type.
- * <br>
- * uint8 represents integer values between 0 and 255, inclusively. The Java counterpart of
- * Yang uint8 built-in type is {@link Short}.
+ * Implementation of Yang uint8 built-in type. <br>
+ * uint8 represents integer values between 0 and 255, inclusively.
  *
  * @see AbstractUnsignedInteger
  */
 public final class Uint8 extends AbstractUnsignedInteger {
-
+    public static final int MAX_VALUE = 255;
     private static final QName name = BaseTypes.constructQName("uint8");
     private final Short defaultValue = null;
-    private static final String description =
-            "uint8  represents integer values between 0 and 255, inclusively.";
+    private static final String description = "uint8  represents integer values between 0 and 255, inclusively.";
     private final UnsignedIntegerTypeDefinition baseType;
 
     public Uint8(final SchemaPath path) {
-        super(path, name, description, Short.MIN_VALUE, Short.MAX_VALUE, "");
+        super(path, name, description, MAX_VALUE, "");
         this.baseType = this;
     }
 
     /*
      * (non-Javadoc)
      *
-     * @see org.opendaylight.controller.yang.model.api.TypeDefinition#getBaseType()
+     * @see
+     * org.opendaylight.controller.yang.model.api.TypeDefinition#getBaseType()
      */
     @Override
     public UnsignedIntegerTypeDefinition getBaseType() {
@@ -45,7 +43,9 @@ public final class Uint8 extends AbstractUnsignedInteger {
     /*
      * (non-Javadoc)
      *
-     * @see org.opendaylight.controller.yang.model.api.TypeDefinition#getDefaultValue()
+     * @see
+     * org.opendaylight.controller.yang.model.api.TypeDefinition#getDefaultValue
+     * ()
      */
     @Override
     public Object getDefaultValue() {
@@ -56,8 +56,7 @@ public final class Uint8 extends AbstractUnsignedInteger {
     public int hashCode() {
         final int prime = 31;
         int result = super.hashCode();
-        result = prime * result
-                + ((defaultValue == null) ? 0 : defaultValue.hashCode());
+        result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());
         return result;
     }
 
@@ -93,4 +92,5 @@ public final class Uint8 extends AbstractUnsignedInteger {
         builder.append("]");
         return builder.toString();
     }
+
 }
@@ -6,7 +6,7 @@
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 import java.io.Serializable;
 import java.util.ArrayList;
@@ -14,7 +14,6 @@ import java.util.Date;
 import java.util.List;
 
 import org.opendaylight.controller.sal.authorization.UserLevel;
-import org.opendaylight.controller.usermanager.ODLUserLevel;
 import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 
@@ -6,7 +6,7 @@
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
-package org.opendaylight.controller.usermanager.internal;
+package org.opendaylight.controller.usermanager;
 
 import java.util.Arrays;
 import java.util.List;
@@ -16,6 +16,7 @@ import org.junit.BeforeClass;
 import org.junit.Test;
 
 import org.opendaylight.controller.sal.authorization.UserLevel;
+import org.opendaylight.controller.usermanager.AuthenticatedUser;
 import org.springframework.security.core.GrantedAuthority;
 
 public class AuthenticatedUserTest {
index faa6e3b96fe4ac5b0df16c1dc274cd812edf443a..9d2ad05765dcc5085247c1aa23025a45aad3d3b5 100644 (file)
@@ -43,6 +43,7 @@ import org.opendaylight.controller.sal.utils.ObjectReader;
 import org.opendaylight.controller.sal.utils.ObjectWriter;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.usermanager.AuthResponse;
+import org.opendaylight.controller.usermanager.AuthenticatedUser;
 import org.opendaylight.controller.usermanager.AuthorizationConfig;
 import org.opendaylight.controller.usermanager.IAAAProvider;
 import org.opendaylight.controller.usermanager.ISessionManager;
@@ -51,7 +52,6 @@ import org.opendaylight.controller.usermanager.ServerConfig;
 import org.opendaylight.controller.usermanager.UserConfig;
 import org.opendaylight.controller.usermanager.security.SessionManager;
 import org.opendaylight.controller.usermanager.security.UserSecurityContextRepository;
-import org.opendaylight.controller.usermanager.internal.AuthenticatedUser;
 
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.FrameworkUtil;
index e8748d8200d23430324fa2ded147ed95aacab9a8..e84396b0f49cc8cc9bab1126ec633d77a0ec2036 100644 (file)
@@ -23,6 +23,7 @@ import org.opendaylight.controller.sal.authorization.AuthResultEnum;
 import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.usermanager.AuthResponse;
+import org.opendaylight.controller.usermanager.AuthenticatedUser;
 import org.opendaylight.controller.usermanager.IAAAProvider;
 import org.opendaylight.controller.usermanager.IUserManager;
 import org.opendaylight.controller.usermanager.ServerConfig;
index 188be8aee6f1ee4865b159d1f2225ec6f1534021..534c2c293c9c9fecc9bf8467fc74d0e237261ac9 100644 (file)
@@ -20,7 +20,6 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.codehaus.jackson.map.ObjectMapper;
-import org.opendaylight.controller.usermanager.IUserManager;
 import org.opendaylight.controller.web.DaylightWebUtil;
 import org.opendaylight.controller.web.IDaylightWeb;
 import org.springframework.stereotype.Controller;
@@ -30,12 +29,14 @@ import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting;
 import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig;
+import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.opendaylight.controller.sal.core.Config;
 import org.opendaylight.controller.sal.core.Name;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.Tier;
+import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.HexEncode;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
@@ -82,13 +83,20 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/nodesLearnt", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getNodesLearnt(HttpServletRequest request, @RequestParam(required = false) String container) {
+    public DevicesJsonBean getNodesLearnt(HttpServletRequest request,
+            @RequestParam(required = false) String container) {
         Gson gson = new Gson();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
         List<Map<String, String>> nodeData = new ArrayList<Map<String, String>>();
-        if (switchManager != null) {
+        if (switchManager != null && privilege != Privilege.NONE) {
             for (Switch device : switchManager.getNetworkDevices()) {
                 HashMap<String, String> nodeDatum = new HashMap<String, String>();
                 Node node = device.getNode();
@@ -174,6 +182,7 @@ public class Devices implements IDaylightWeb {
 
         DevicesJsonBean result = new DevicesJsonBean();
         result.setNodeData(nodeData);
+        result.setPrivilege(privilege);
         List<String> columnNames = new ArrayList<String>();
         columnNames.add("Node ID");
         columnNames.add("Node Name");
@@ -199,13 +208,19 @@ public class Devices implements IDaylightWeb {
             @RequestParam("nodeId") String nodeId,
             @RequestParam("tier") String tier,
             @RequestParam("operationMode") String operationMode,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil
+                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
@@ -224,9 +239,16 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/staticRoutes", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getStaticRoutes(HttpServletRequest request, @RequestParam(required = false) String container) {
+    public DevicesJsonBean getStaticRoutes(HttpServletRequest request,
+            @RequestParam(required = false) String container) {
         Gson gson = new Gson();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
         IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
                 .getInstance(IForwardingStaticRouting.class, containerName,
                         this);
@@ -239,16 +261,19 @@ public class Devices implements IDaylightWeb {
         if (routeConfigs == null) {
             return null;
         }
-        for (StaticRouteConfig conf : routeConfigs.values()) {
-            Map<String, String> staticRoute = new HashMap<String, String>();
-            staticRoute.put("name", conf.getName());
-            staticRoute.put("staticRoute", conf.getStaticRoute());
-            staticRoute.put("nextHopType", conf.getNextHopType());
-            staticRoute.put("nextHop", conf.getNextHop());
-            staticRoute.put("json", gson.toJson(conf));
-            staticRoutes.add(staticRoute);
+        if (privilege != Privilege.NONE) {
+            for (StaticRouteConfig conf : routeConfigs.values()) {
+                Map<String, String> staticRoute = new HashMap<String, String>();
+                staticRoute.put("name", conf.getName());
+                staticRoute.put("staticRoute", conf.getStaticRoute());
+                staticRoute.put("nextHopType", conf.getNextHopType());
+                staticRoute.put("nextHop", conf.getNextHop());
+                staticRoute.put("json", gson.toJson(conf));
+                staticRoutes.add(staticRoute);
+            }
         }
         DevicesJsonBean result = new DevicesJsonBean();
+        result.setPrivilege(privilege);
         result.setColumnNames(StaticRouteConfig.getGuiFieldsNames());
         result.setNodeData(staticRoutes);
         return result;
@@ -260,13 +285,19 @@ public class Devices implements IDaylightWeb {
             @RequestParam("routeName") String routeName,
             @RequestParam("staticRoute") String staticRoute,
             @RequestParam("nextHop") String nextHop,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil
+                .getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean result = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
                     .getInstance(IForwardingStaticRouting.class, containerName,
@@ -294,13 +325,18 @@ public class Devices implements IDaylightWeb {
     @ResponseBody
     public StatusJsonBean deleteStaticRoute(
             @RequestParam("routesToDelete") String routesToDelete,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper
                     .getInstance(IForwardingStaticRouting.class, containerName,
@@ -329,22 +365,33 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/subnets", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getSubnetGateways(HttpServletRequest request, @RequestParam(required = false) String container) {
+    public DevicesJsonBean getSubnetGateways(HttpServletRequest request,
+            @RequestParam(required = false) String container) {
         Gson gson = new Gson();
         List<Map<String, String>> subnets = new ArrayList<Map<String, String>>();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
-        if (switchManager != null) {
-            for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
-                Map<String, String> subnet = new HashMap<String, String>();
-                subnet.put("name", conf.getName());
-                subnet.put("subnet", conf.getSubnet());
-                subnet.put("json", gson.toJson(conf));
-                subnets.add(subnet);
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(
+                userName, containerName, this);
+
+        if (privilege != Privilege.NONE) {
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                    .getInstance(ISwitchManager.class, containerName, this);
+            if (switchManager != null) {
+                for (SubnetConfig conf : switchManager.getSubnetsConfigList()) {
+                    Map<String, String> subnet = new HashMap<String, String>();
+                    subnet.put("name", conf.getName());
+                    subnet.put("subnet", conf.getSubnet());
+                    subnet.put("json", gson.toJson(conf));
+                    subnets.add(subnet);
+                }
             }
         }
         DevicesJsonBean result = new DevicesJsonBean();
+        result.setPrivilege(privilege);
         result.setColumnNames(SubnetConfig.getGuiFieldsNames());
         result.setNodeData(subnets);
         return result;
@@ -355,13 +402,18 @@ public class Devices implements IDaylightWeb {
     public StatusJsonBean addSubnetGateways(
             @RequestParam("gatewayName") String gatewayName,
             @RequestParam("gatewayIPAddress") String gatewayIPAddress,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
@@ -386,13 +438,18 @@ public class Devices implements IDaylightWeb {
     @ResponseBody
     public StatusJsonBean deleteSubnetGateways(
             @RequestParam("gatewaysToDelete") String gatewaysToDelete,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, container, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
@@ -419,14 +476,18 @@ public class Devices implements IDaylightWeb {
     public StatusJsonBean addSubnetGatewayPort(
             @RequestParam("portsName") String portsName,
             @RequestParam("ports") String ports,
-            @RequestParam("nodeId") String nodeId,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            @RequestParam("nodeId") String nodeId, HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
@@ -453,13 +514,18 @@ public class Devices implements IDaylightWeb {
     public StatusJsonBean deleteSubnetGatewayPort(
             @RequestParam("gatewayName") String gatewayName,
             @RequestParam("nodePort") String nodePort,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
         try {
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
@@ -483,38 +549,51 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/spanPorts", method = RequestMethod.GET)
     @ResponseBody
-    public DevicesJsonBean getSpanPorts(HttpServletRequest request, @RequestParam(required = false) String container) {
+    public DevicesJsonBean getSpanPorts(HttpServletRequest request,
+            @RequestParam(required = false) String container) {
         Gson gson = new Gson();
-        List<String> spanConfigs_json = new ArrayList<String>();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
-        if (switchManager != null) {
-            for (SpanConfig conf : switchManager.getSpanConfigList()) {
-                spanConfigs_json.add(gson.toJson(conf));
-            }
-        }
-        ObjectMapper mapper = new ObjectMapper();
         List<Map<String, String>> spanConfigs = new ArrayList<Map<String, String>>();
-        for (String config_json : spanConfigs_json) {
-            try {
-                @SuppressWarnings("unchecked")
-                Map<String, String> config_data = mapper.readValue(config_json,
-                        HashMap.class);
-                Map<String, String> config = new HashMap<String, String>();
-                for (String name : config_data.keySet()) {
-                    config.put(name, config_data.get(name));
-                    // Add switch name value (non-configuration field)
-                    config.put("nodeName",
-                            getNodeDesc(config_data.get("nodeId"), containerName));
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(
+                userName, containerName, this);
+
+        if (privilege != Privilege.NONE) {
+            List<String> spanConfigs_json = new ArrayList<String>();
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                    .getInstance(ISwitchManager.class, containerName, this);
+            if (switchManager != null) {
+                for (SpanConfig conf : switchManager.getSpanConfigList()) {
+                    spanConfigs_json.add(gson.toJson(conf));
+                }
+            }
+            ObjectMapper mapper = new ObjectMapper();
+
+            for (String config_json : spanConfigs_json) {
+                try {
+                    @SuppressWarnings("unchecked")
+                    Map<String, String> config_data = mapper.readValue(config_json,
+                            HashMap.class);
+                    Map<String, String> config = new HashMap<String, String>();
+                    for (String name : config_data.keySet()) {
+                        config.put(name, config_data.get(name));
+                        // Add switch name value (non-configuration field)
+                        config.put("nodeName",
+                                getNodeDesc(config_data.get("nodeId"), containerName));
+                    }
+                    config.put("json", config_json);
+                    spanConfigs.add(config);
+                } catch (Exception e) {
+                    // TODO: Handle the exception.
                 }
-                config.put("json", config_json);
-                spanConfigs.add(config);
-            } catch (Exception e) {
-                // TODO: Handle the exception.
             }
         }
+
         DevicesJsonBean result = new DevicesJsonBean();
+        result.setPrivilege(privilege);
         result.setColumnNames(SpanConfig.getGuiFieldsNames());
         result.setNodeData(spanConfigs);
         return result;
@@ -522,8 +601,18 @@ public class Devices implements IDaylightWeb {
 
     @RequestMapping(value = "/nodeports")
     @ResponseBody
-    public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+    public Map<String, Object> getNodePorts(HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+            return null;
+        }
+
+
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
         if (switchManager == null) {
@@ -537,7 +626,7 @@ public class Devices implements IDaylightWeb {
             port = new HashMap<Short, String>(); // new port
             Set<NodeConnector> nodeConnectorSet = node.getNodeConnectors();
 
-            if (nodeConnectorSet != null)
+            if (nodeConnectorSet != null) {
                 for (NodeConnector nodeConnector : nodeConnectorSet) {
                     String nodeConnectorName = ((Name) switchManager
                             .getNodeConnectorProp(nodeConnector,
@@ -545,6 +634,7 @@ public class Devices implements IDaylightWeb {
                     port.put((Short) nodeConnector.getID(), nodeConnectorName
                             + "(" + nodeConnector.getID() + ")");
                 }
+            }
 
             nodes.put(node.getNode().toString(), port);
         }
@@ -556,15 +646,20 @@ public class Devices implements IDaylightWeb {
     @ResponseBody
     public StatusJsonBean addSpanPort(
             @RequestParam("jsonData") String jsonData,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
             Gson gson = new Gson();
-            String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
             SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class);
@@ -588,15 +683,20 @@ public class Devices implements IDaylightWeb {
     @ResponseBody
     public StatusJsonBean deleteSpanPorts(
             @RequestParam("spanPortsToDelete") String spanPortsToDelete,
-            HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
+            HttpServletRequest request,
+            @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT
+                .toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return unauthorizedMessage();
         }
 
         StatusJsonBean resultBean = new StatusJsonBean();
         try {
             Gson gson = new Gson();
-            String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
             ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                     .getInstance(ISwitchManager.class, containerName, this);
             String[] spans = spanPortsToDelete.split("###");
@@ -634,26 +734,6 @@ public class Devices implements IDaylightWeb {
                 : description;
     }
 
-    /**
-     * Is the operation permitted for the given level
-     *
-     * @param level
-     */
-    private boolean authorize(UserLevel level, HttpServletRequest request) {
-        IUserManager userManager = (IUserManager) ServiceHelper
-                .getGlobalInstance(IUserManager.class, this);
-        if (userManager == null) {
-            return false;
-        }
-
-        String username = request.getUserPrincipal().getName();
-        UserLevel userLevel = userManager.getUserLevel(username);
-        if (userLevel.toNumber() <= level.toNumber()) {
-            return true;
-        }
-        return false;
-    }
-
     private StatusJsonBean unauthorizedMessage() {
         StatusJsonBean message = new StatusJsonBean();
         message.setStatus(false);
index 6b77f119edcea1bf6e656ffe46eef6e9b16d39aa..ce0b3763e06bb26f1e3c46e657e8fa4f2e2c5447 100644 (file)
@@ -11,9 +11,12 @@ package org.opendaylight.controller.devices.web;
 import java.util.List;
 import java.util.Map;
 
+import org.opendaylight.controller.sal.authorization.Privilege;
+
 public class DevicesJsonBean {
     private List<String> columnNames;
     private List<Map<String, String>> nodeData;
+    private Privilege privilege;
 
     public List<String> getColumnNames() {
         return columnNames;
@@ -30,4 +33,12 @@ public class DevicesJsonBean {
     public void setNodeData(List<Map<String, String>> nodeData) {
         this.nodeData = nodeData;
     }
+
+    public void setPrivilege(Privilege privilege) {
+        this.privilege = privilege;
+    }
+
+    public Privilege getPrivilege() {
+        return privilege;
+    }
 }
index 96b16bf92cc2da50be0c06da2ac3e946edca8b7d..ce59238be60b106ecacba66e8207aeb259955b42 100644 (file)
@@ -104,18 +104,27 @@ one.f.switchmanager.nodesLearnt = {
        modal : {
                initialize: {
                        updateNode: function(evt) {
-                               var nodeId = decodeURIComponent(evt.target.id);
-                               var h3 = "Update Node Information";
-                   var footer = one.f.switchmanager.nodesLearnt.modal.footer.updateNode();
-                   var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.modal, h3, "", footer);
-                   
-                   // bind save button
-                   $('#' + one.f.switchmanager.nodesLearnt.id.modal.save, $modal).click(function() {
-                       one.f.switchmanager.nodesLearnt.modal.save($modal);
-                   });
-                   // inject body (nodePorts)
                    one.f.switchmanager.nodesLearnt.ajax.main(one.f.switchmanager.rootUrl + "/tiers", function(tiers) {
-                       var $body = one.f.switchmanager.nodesLearnt.modal.body.updateNode(nodeId, evt.target.switchDetails, tiers);
+
+                    var nodeId = decodeURIComponent(evt.target.id);
+                    var h3;
+                    var footer = [];
+                    var $body = one.f.switchmanager.nodesLearnt.modal.body.updateNode(nodeId, evt.target.switchDetails, tiers);
+                    if ( (one.main.registry == undefined || one.main.registry.container == 'default') && evt.target.privilege == 'WRITE'){
+                        h3 = "Update Node Information";
+                        footer = one.f.switchmanager.nodesLearnt.modal.footer.updateNode();
+                    } else { //disable node edit
+                        $body.find('*').attr('disabled', 'disabled');
+                        h3 = 'Node Information';
+                    }
+
+                    var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.modal, h3, "", footer);
+                    // bind save button
+                    $('#' + one.f.switchmanager.nodesLearnt.id.modal.save, $modal).click(function() {
+                        one.f.switchmanager.nodesLearnt.modal.save($modal);
+                    });
+
+                       // inject body (nodePorts)
                        one.lib.modal.inject.body($modal, $body);
                        $modal.modal();
                    });
@@ -160,7 +169,6 @@ one.f.switchmanager.nodesLearnt = {
                                $select.attr('id', one.f.switchmanager.nodesLearnt.id.modal.form.operationMode);
                                $select.val(switchDetails["mode"]);
                                $fieldset.append($label).append($select);
-                               
                                $form.append($fieldset);
                                return $form;
                        },
@@ -205,11 +213,10 @@ one.f.switchmanager.nodesLearnt = {
                footer: {
                        updateNode: function() {
                                var footer = [];
-                               if(one.role < 2) {
-                                       var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.nodesLearnt.id.modal.save, "btn-success", "");
-                           var $saveButton = one.lib.dashlet.button.button(saveButton);
-                           footer.push($saveButton);
-                               }
+                var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.nodesLearnt.id.modal.save, "btn-success", "");
+                var $saveButton = one.lib.dashlet.button.button(saveButton);
+                footer.push($saveButton);
+
                    return footer;
                        },
                        popout: function() {
@@ -226,14 +233,17 @@ one.f.switchmanager.nodesLearnt = {
                                var tr = {};
                                var entry = [];
                                var nodenameentry = value["nodeName"] ? value["nodeName"] : "Click to update";
+
                                // TODO: Move anchor tag creation to one.lib.form.
-                               var aTag = document.createElement("a");
-                               aTag.setAttribute("id", encodeURIComponent(value["nodeId"]));
-                               aTag.switchDetails = value;
-                               aTag.addEventListener("click", one.f.switchmanager.nodesLearnt.modal.initialize.updateNode);
-                               aTag.addEventListener("mouseover", function(evt) {
-                                       evt.target.style.cursor = "pointer";
-                               }, false);
+                               var aTag;
+                aTag = document.createElement("a");
+                aTag.privilege = data.privilege;
+                aTag.addEventListener("click", one.f.switchmanager.nodesLearnt.modal.initialize.updateNode);
+                aTag.addEventListener("mouseover", function(evt) {
+                    evt.target.style.cursor = "pointer";
+                }, false);
+                aTag.setAttribute("id", encodeURIComponent(value["nodeId"]));
+                aTag.switchDetails = value;
                                aTag.innerHTML = nodenameentry;
                                entry.push(aTag);
                                entry.push(value["nodeId"]);
@@ -287,55 +297,56 @@ one.f.switchmanager.subnetGatewayConfig = {
                one.lib.dashlet.empty($dashlet);
                $dashlet.append(one.lib.dashlet.header(one.f.dashlet.subnetGatewayConfig.name));
                // Add gateway IP Address button
-               if(one.role < 2) {
-                       var button = one.lib.dashlet.button.single("Add Gateway IP Address", 
-                                       one.f.switchmanager.subnetGatewayConfig.id.dashlet.addIPAddress, "btn-primary", "btn-mini");
-               var $button = one.lib.dashlet.button.button(button);
-               $button.click(function() {
-                       var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.gateway();
-                   $modal.modal();
-               });
-                       $dashlet.append($button);
-               
-               
-                       // Delete gateway ip address button
-               var button = one.lib.dashlet.button.single("Delete Gateway IP Address(es)", 
-                               one.f.switchmanager.subnetGatewayConfig.id.dashlet.removeIPAddress, "btn-primary", "btn-mini");
-               var $button = one.lib.dashlet.button.button(button);
-               $button.click(function() {
-                       var requestData = {};
-                       var gatewaysToDelete = [];
-                       var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
-                       checkedCheckBoxes.each(function(index, value) {
-                               gatewaysToDelete.push(checkedCheckBoxes[index].id);
-                       }); 
-                       if(gatewaysToDelete.length > 0) {
-                               requestData["gatewaysToDelete"] = gatewaysToDelete.toString();
-                       var url = one.f.switchmanager.rootUrl + "/subnetGateway/delete";
-                               one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) {
-                                       if(response.status == true) {
-                                               // refresh dashlet by passing dashlet div as param
-                               one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet"));
-                                       } else {
-                                               alert(response.message);
-                                       }
-                               });
-                       } 
-               });
-               $dashlet.append($button);
-       
-                       // Add Ports button
-                       var button = one.lib.dashlet.button.single("Add Ports", 
-                                       one.f.switchmanager.subnetGatewayConfig.id.dashlet.addPorts, "btn-primary", "btn-mini");
-               var $button = one.lib.dashlet.button.button(button);
-               $button.click(function() {
-                       var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.ports();
-                   $modal.modal();
-               });
-                       $dashlet.append($button);
-               }
                var url = one.f.switchmanager.rootUrl + "/subnets";
                one.f.switchmanager.subnetGatewayConfig.ajax.main(url, {}, function(content) {
+
+            if (content.privilege === 'WRITE') {
+                var button = one.lib.dashlet.button.single("Add Gateway IP Address",
+                    one.f.switchmanager.subnetGatewayConfig.id.dashlet.addIPAddress, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+                $button.click(function() {
+                    var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.gateway();
+                    $modal.modal();
+                });
+                $dashlet.append($button);
+
+                // Delete gateway ip address button
+                var button = one.lib.dashlet.button.single("Delete Gateway IP Address(es)",
+                    one.f.switchmanager.subnetGatewayConfig.id.dashlet.removeIPAddress, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+                $button.click(function() {
+                    var requestData = {};
+                    var gatewaysToDelete = [];
+                    var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
+                    checkedCheckBoxes.each(function(index, value) {
+                        gatewaysToDelete.push(checkedCheckBoxes[index].id);
+                    });
+                    if (gatewaysToDelete.length > 0) {
+                        requestData["gatewaysToDelete"] = gatewaysToDelete.toString();
+                        var url = one.f.switchmanager.rootUrl + "/subnetGateway/delete";
+                        one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) {
+                            if (response.status == true) {
+                                // refresh dashlet by passing dashlet div as param
+                                one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet"));
+                            } else {
+                                alert(response.message);
+                            }
+                        });
+                    }
+                });
+                $dashlet.append($button);
+
+                // Add Ports button
+                var button = one.lib.dashlet.button.single("Add Ports",
+                    one.f.switchmanager.subnetGatewayConfig.id.dashlet.addPorts, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+                $button.click(function() {
+                    var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.ports();
+                    $modal.modal();
+                });
+                $dashlet.append($button);
+            }
+
                        var body = one.f.switchmanager.subnetGatewayConfig.data.devices(content);
                        // first column contains checkbox. no need for header
                        content.columnNames.splice(0,0," ");
@@ -502,11 +513,9 @@ one.f.switchmanager.subnetGatewayConfig = {
                },
                footer : function() {
             var footer = [];
-            if(one.role < 2) {
-                var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.subnetGatewayConfig.id.modal.save, "btn-success", "");
-                 var $saveButton = one.lib.dashlet.button.button(saveButton);
-                 footer.push($saveButton);
-            }
+            var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.subnetGatewayConfig.id.modal.save, "btn-success", "");
+            var $saveButton = one.lib.dashlet.button.button(saveButton);
+            footer.push($saveButton);
             return footer;
         }
        },
@@ -591,47 +600,47 @@ one.f.switchmanager.staticRouteConfig = {
        dashlet: function($dashlet) {
                one.lib.dashlet.empty($dashlet);
                
-               if(one.role < 2) {
-                       // Add static route button
-                       var button = one.lib.dashlet.button.single("Add Static Route", 
-                                       one.f.switchmanager.staticRouteConfig.id.dashlet.add, "btn-primary", "btn-mini");
-               var $button = one.lib.dashlet.button.button(button);
-               $button.click(function() {
-                       var $modal = one.f.switchmanager.staticRouteConfig.modal.initialize();
-                   $modal.modal();
-               });
-               $dashlet.append(one.lib.dashlet.header(one.f.dashlet.staticRouteConfig.name));
-               $dashlet.append($button);
-               
-               // Delete static route button
-               var button = one.lib.dashlet.button.single("Delete Static Route(s)", 
-                               one.f.switchmanager.staticRouteConfig.id.dashlet.remove, "btn-primary", "btn-mini");
-               var $button = one.lib.dashlet.button.button(button);
-               $button.click(function() {
-                       var requestData = {};
-                       var routesToDelete = [];
-                       var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
-                       checkedCheckBoxes.each(function(index, value) {
-                               routesToDelete.push(checkedCheckBoxes[index].id);
-                       }); 
-                       if(routesToDelete.length > 0) {
-                               requestData["routesToDelete"] = routesToDelete.toString();
-                       var url = one.f.switchmanager.rootUrl + "/staticRoute/delete";
-                               one.f.switchmanager.staticRouteConfig.ajax.main(url, requestData, function(response) {
-                                       if(response.status == true) {
-                                               // refresh dashlet by passing dashlet div as param
-                               one.f.switchmanager.staticRouteConfig.dashlet($("#left-bottom .dashlet"));
-                                       } else {
-                                               alert(response.message);
-                                       }
-                               });
-                       } 
-               });
-               $dashlet.append($button);
-               }
-               
+
                var url = one.f.switchmanager.rootUrl + "/staticRoutes";
                one.f.switchmanager.staticRouteConfig.ajax.main(url, {}, function(content) {
+
+            if (content.privilege === 'WRITE') {
+                // Add static route button
+                var button = one.lib.dashlet.button.single("Add Static Route", one.f.switchmanager.staticRouteConfig.id.dashlet.add, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+                $button.click(function() {
+                    var $modal = one.f.switchmanager.staticRouteConfig.modal.initialize();
+                    $modal.modal();
+                });
+                $dashlet.append(one.lib.dashlet.header(one.f.dashlet.staticRouteConfig.name));
+                $dashlet.append($button);
+
+                // Delete static route button
+                var button = one.lib.dashlet.button.single("Delete Static Route(s)", one.f.switchmanager.staticRouteConfig.id.dashlet.remove, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+                $button.click(function() {
+                    var requestData = {};
+                    var routesToDelete = [];
+                    var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
+                    checkedCheckBoxes.each(function(index, value) {
+                        routesToDelete.push(checkedCheckBoxes[index].id);
+                    });
+                    if (routesToDelete.length > 0) {
+                        requestData["routesToDelete"] = routesToDelete.toString();
+                        var url = one.f.switchmanager.rootUrl + "/staticRoute/delete";
+                        one.f.switchmanager.staticRouteConfig.ajax.main(url, requestData, function(response) {
+                            if (response.status == true) {
+                                // refresh dashlet by passing dashlet div as param
+                                one.f.switchmanager.staticRouteConfig.dashlet($("#left-bottom .dashlet"));
+                            } else {
+                                alert(response.message);
+                            }
+                        });
+                    }
+                });
+                $dashlet.append($button);
+            }
+
                        var body = one.f.switchmanager.staticRouteConfig.data.staticRouteConfig(content);
                        // first column contains checkbox. no need for header
                        content.columnNames.splice(0,0," ");
@@ -712,11 +721,9 @@ one.f.switchmanager.staticRouteConfig = {
         },
                footer : function() {
             var footer = [];
-            if (one.role < 2) {
-                var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.staticRouteConfig.id.modal.save, "btn-success", "");
-                 var $saveButton = one.lib.dashlet.button.button(saveButton);
-                 footer.push($saveButton);
-            }
+            var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.staticRouteConfig.id.modal.save, "btn-success", "");
+            var $saveButton = one.lib.dashlet.button.button(saveButton);
+            footer.push($saveButton);
             return footer;
         }
        },
@@ -761,51 +768,52 @@ one.f.switchmanager.spanPortConfig = {
        },
        dashlet: function($dashlet) {
                one.lib.dashlet.empty($dashlet);
-               if(one.role < 2) {
-
-                       // Add span port button
-                       var button = one.lib.dashlet.button.single("Add Span Port", one.f.switchmanager.spanPortConfig.id.dashlet.add, "btn-primary", "btn-mini");
-                       var $button = one.lib.dashlet.button.button(button);
-
-                       $button.click(function() {
-                               var $modal = one.f.switchmanager.spanPortConfig.modal.initialize();
-                               $modal.modal();
-                       });
-                       $dashlet.append(one.lib.dashlet.header(one.f.dashlet.spanPortConfig.name));
-                       $dashlet.append($button);
-
-                       // Delete span port button
-                       var button = one.lib.dashlet.button.single("Delete SPAN Port(s)", 
-                                       one.f.switchmanager.spanPortConfig.id.dashlet.remove, "btn-primary", "btn-mini");
-                       var $button = one.lib.dashlet.button.button(button);
-                       $button.click(function() {
-
-                               var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
-                               if(checkedCheckBoxes.length > 0) {
-                                       var spanPortsToDelete = "";
-                                       checkedCheckBoxes.each(function(index, value) {
-                                               spanPortsToDelete += checkedCheckBoxes[index].spanPort + "###";
-                                       }); 
-
-                                       var requestData = {};
-                                       requestData["spanPortsToDelete"] = spanPortsToDelete;
-                                       var url = one.f.switchmanager.rootUrl + "/spanPorts/delete";
-                                       one.f.switchmanager.spanPortConfig.ajax.main(url, requestData, function(response) {
-                                               if(response.status == true) {
-                                                       // refresh dashlet by passing dashlet div as param
-                                                       one.f.switchmanager.spanPortConfig.dashlet($("#right-bottom .dashlet"));
-                                               } else {
-                                                       alert(response.message);
-                                               }
-                                       });
-                               }
-                       });
-                       $dashlet.append($button);
-               }
         
         //populate table in dashlet
                var url = one.f.switchmanager.rootUrl + "/spanPorts";
                one.f.switchmanager.spanPortConfig.ajax.main(url, {}, function(content) {
+
+            if (content.privilege === 'WRITE') {
+
+                // Add span port button
+                var button = one.lib.dashlet.button.single("Add Span Port", one.f.switchmanager.spanPortConfig.id.dashlet.add, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+
+                $button.click(function() {
+                    var $modal = one.f.switchmanager.spanPortConfig.modal.initialize();
+                    $modal.modal();
+                });
+                $dashlet.append(one.lib.dashlet.header(one.f.dashlet.spanPortConfig.name));
+                $dashlet.append($button);
+
+                // Delete span port button
+                var button = one.lib.dashlet.button.single("Delete SPAN Port(s)", one.f.switchmanager.spanPortConfig.id.dashlet.remove, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+                $button.click(function() {
+
+                    var checkedCheckBoxes = $("input:checked", $(this).closest(".dashlet").find("table"));
+                    if (checkedCheckBoxes.length > 0) {
+                        var spanPortsToDelete = "";
+                        checkedCheckBoxes.each(function(index, value) {
+                            spanPortsToDelete += checkedCheckBoxes[index].spanPort + "###";
+                        });
+
+                        var requestData = {};
+                        requestData["spanPortsToDelete"] = spanPortsToDelete;
+                        var url = one.f.switchmanager.rootUrl + "/spanPorts/delete";
+                        one.f.switchmanager.spanPortConfig.ajax.main(url, requestData, function(response) {
+                            if (response.status == true) {
+                                // refresh dashlet by passing dashlet div as param
+                                one.f.switchmanager.spanPortConfig.dashlet($("#right-bottom .dashlet"));
+                            } else {
+                                alert(response.message);
+                            }
+                        });
+                    }
+                });
+                $dashlet.append($button);
+            }
+
                        var body = one.f.switchmanager.spanPortConfig.data.devices(content);
                        // first column contains the checkbox. no header required.
                        content.columnNames.splice(0,0," ");
@@ -911,11 +919,9 @@ one.f.switchmanager.spanPortConfig = {
         },
                footer : function() {
             var footer = [];
-            if (one.role < 2) {
-                var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.spanPortConfig.id.modal.save, "btn-success", "");
-                var $saveButton = one.lib.dashlet.button.button(saveButton);
-                footer.push($saveButton);
-            }
+            var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.spanPortConfig.id.modal.save, "btn-success", "");
+            var $saveButton = one.lib.dashlet.button.button(saveButton);
+            footer.push($saveButton);
             return footer;
         }
        },
index e1cfcc57087d4c1ca340f0fc13dccfd7d2ab5fb1..c4341347d088c95944987f1470da8633adece44a 100644 (file)
@@ -18,17 +18,18 @@ import javax.servlet.http.HttpServletRequest;
 
 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
+import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.opendaylight.controller.sal.core.Name;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
 import org.opendaylight.controller.sal.utils.Status;
 import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.switchmanager.Switch;
 import org.opendaylight.controller.switchmanager.SwitchConfig;
-import org.opendaylight.controller.usermanager.IUserManager;
 import org.opendaylight.controller.web.DaylightWebUtil;
 import org.opendaylight.controller.web.IDaylightWeb;
 import org.springframework.stereotype.Controller;
@@ -74,8 +75,15 @@ public class Flows implements IDaylightWeb {
 
     @RequestMapping(value = "/main")
     @ResponseBody
-    public Set<Map<String, Object>> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+    public Map<String, Object> getFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+        if (privilege  == Privilege.NONE) {
+            return null;
+        }
 
         // fetch frm
         IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
@@ -93,7 +101,7 @@ public class Flows implements IDaylightWeb {
 
         // get static flow list
         List<FlowConfig> staticFlowList = frm.getStaticFlows();
-        Set<Map<String, Object>> output = new HashSet<Map<String, Object>>();
+        Set<Map<String, Object>> flowSet = new HashSet<Map<String, Object>>();
         for (FlowConfig flowConfig : staticFlowList) {
             Map<String, Object> entry = new HashMap<String, Object>();
             entry.put("flow", flowConfig);
@@ -103,16 +111,25 @@ public class Flows implements IDaylightWeb {
             entry.put("node", (description.isEmpty() || description
                     .equalsIgnoreCase("none")) ? node.toString() : description);
             entry.put("nodeId", node.toString());
-            output.add(entry);
+            flowSet.add(entry);
         }
 
+        Map <String, Object> output = new HashMap<String, Object>(2);
+        output.put("flows", flowSet);
+        output.put("privilege", privilege);
         return output;
     }
 
     @RequestMapping(value = "/node-ports")
     @ResponseBody
     public Map<String, Object> getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+            return null;
+        }
 
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
@@ -159,7 +176,13 @@ public class Flows implements IDaylightWeb {
     @RequestMapping(value = "/node-flows")
     @ResponseBody
     public Map<String, Object> getNodeFlows(HttpServletRequest request, @RequestParam(required = false) String container) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) {
+            return null;
+        }
 
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
                 .getInstance(ISwitchManager.class, containerName, this);
@@ -198,12 +221,14 @@ public class Flows implements IDaylightWeb {
             @RequestParam(required = false) String body,
             @RequestParam(required = true) String nodeId,
             HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return "Operation not authorized";
         }
 
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
         IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
                 .getInstance(IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
@@ -229,12 +254,14 @@ public class Flows implements IDaylightWeb {
             @PathVariable("name") String name,
             @RequestParam(required = true) String action,
             HttpServletRequest request, @RequestParam(required = false) String container) {
-        if (!isUserAuthorized(UserLevel.NETWORKADMIN, request)) {
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Authorization check
+        String userName = request.getUserPrincipal().getName();
+        if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) {
             return "Operation not authorized";
         }
 
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-
         IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper
                 .getInstance(IForwardingRulesManager.class, containerName, this);
         if (frm == null) {
@@ -257,25 +284,4 @@ public class Flows implements IDaylightWeb {
         return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result
                 .getDescription();
     }
-
-    /**
-     * Returns whether the current user's level is same or above the required
-     * authorization level.
-     *
-     * @param requiredLevel
-     *            the authorization level required
-     */
-    private boolean isUserAuthorized(UserLevel requiredLevel,
-            HttpServletRequest request) {
-        IUserManager userManager = (IUserManager) ServiceHelper
-                .getGlobalInstance(IUserManager.class, this);
-        if (userManager == null) {
-            return false;
-        }
-
-        String username = request.getUserPrincipal().getName();
-        UserLevel userLevel = userManager.getUserLevel(username);
-        return (userLevel.ordinal() <= requiredLevel.ordinal());
-    }
-
 }
index f92e596b0aab2ecd23f36a7c25ac873c08c219f8..577570f4312a6d0a074aa150f68f6575fd7699e2 100644 (file)
@@ -1,9 +1,9 @@
 
-/* 
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved. 
- * 
- * This program and the accompanying materials are made available under the 
- * terms of the Eclipse Public License v1.0 which accompanies this distribution, 
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
@@ -60,7 +60,7 @@ one.f.nodes = {
     dashlet : function($dashlet) {
         var $h4 = one.lib.dashlet.header("Nodes");
         $dashlet.append($h4);
-        
+
         // load body
         one.f.nodes.ajax.dashlet(function($table) {
                        // total nodes count
@@ -109,14 +109,14 @@ one.f.nodes = {
         dashlet : function(body, callback) {
             var attributes = ['table-striped', 'table-bordered', 'table-hover', 'table-condensed'];
             var $table = one.lib.dashlet.table.table(attributes);
-            
+
             var headers = ['Node', 'Flows'];
             var $thead = one.lib.dashlet.table.header(headers);
             $table.append($thead);
-            
+
             var $tbody = one.lib.dashlet.table.body(body);
             $table.append($tbody);
-            
+
             return $table;
         }
     }
@@ -129,7 +129,7 @@ one.f.detail = {
     dashlet : function($dashlet, details) {
         var $h4 = one.lib.dashlet.header("Flow Details");
         $dashlet.append($h4);
-        
+
         // details
         if (details == undefined) {
                var $none = $(document.createElement('div'));
@@ -137,7 +137,7 @@ one.f.detail = {
             var $p = $(document.createElement('p'));
             $p.text('Please select a flow');
             $p.addClass('text-center').addClass('text-info');
-            
+
             $dashlet.append($none)
                .append($p);
         }
@@ -302,23 +302,32 @@ one.f.flows = {
     },
     registry : {},
     dashlet : function($dashlet, callback) {
-        var $h4 = one.lib.dashlet.header("Flow Entries");
-        
-        if (one.role < 2) {
-               var button = one.lib.dashlet.button.single("Add Flow Entry", one.f.flows.id.dashlet.add, "btn-primary", "btn-mini");
-               var $button = one.lib.dashlet.button.button(button);
-               
-               $button.click(function() {
-                   var $modal = one.f.flows.modal.initialize();
-                   $modal.modal();
-               });
-        }
-        
-        $dashlet.append($h4);
-        if (one.role < 2) $dashlet.append($button);
-        
+
         // load body
         one.f.flows.ajax.dashlet(function($table) {
+
+            var $h4 = one.lib.dashlet.header("Flow Entries");
+
+            $dashlet.append($h4);
+            if (one.f.flows.registry.privilege === 'WRITE') {
+                var button = one.lib.dashlet.button.single("Add Flow Entry", one.f.flows.id.dashlet.add, "btn-primary", "btn-mini");
+                var $button = one.lib.dashlet.button.button(button);
+
+                $button.click(function() {
+                    var $modal = one.f.flows.modal.initialize();
+                    $modal.modal();
+                });
+                $dashlet.append($button);
+
+            }
+
+            // table bindings
+            $table.find('tbody').find('tr').click(function() {
+                var id = $($(this).find('td')[0]).text();
+                var node = $(this).data('id');
+                one.f.flows.detail(id, node);
+            });
+
                        // total flows
                        var flowCount = $table.find('tbody').find('tr').size();
                        // prompt output
@@ -332,13 +341,7 @@ one.f.flows = {
                        $p = $(document.createElement('p'));
                        $p.append(out);
                        $dashlet.append($p);
-            // table bindings
-            $table.find('tbody').find('tr').click(function() {
-                var id = $($(this).find('td')[0]).text();
-                               var node = $(this).data('id');
-                one.f.flows.detail(id, node);
-            });
-            // add to dashlet
+            // add table to dashlet
             $dashlet.append($table);
             // details callback
             if(callback != undefined) callback();
@@ -350,7 +353,7 @@ one.f.flows = {
         $detailDashlet.empty();
         var $h4 = one.lib.dashlet.header("Flow Overview");
         $detailDashlet.append($h4);
-        
+
         // details
         var flows = one.f.flows.registry.flows;
         var flow;
@@ -359,7 +362,7 @@ one.f.flows = {
                 flow = value;
             }
         });
-        if (one.role < 2) {
+        if (one.f.flows.registry.privilege === 'WRITE') {
                // remove button
                var button = one.lib.dashlet.button.single("Remove Flow", one.f.flows.id.dashlet.remove, "btn-danger", "btn-mini");
                var $button = one.lib.dashlet.button.button(button);
@@ -395,11 +398,12 @@ one.f.flows = {
                        }
                    });
                });
+
+               $detailDashlet.append($button).append($toggle);
         }
         // append details
         var body = one.f.detail.data.dashlet(flow);
         var $body = one.f.detail.body.dashlet(body);
-        if (one.role < 2) $detailDashlet.append($button).append($toggle);
         $detailDashlet.append($body);
                var body = one.f.detail.data.description(flow);
                var $body = one.f.detail.body.description(body);
@@ -436,15 +440,15 @@ one.f.flows = {
             },
             footer : function() {
                 var footer = [];
-                
+
                 var removeButton = one.lib.dashlet.button.single("Remove Flow", one.f.flows.id.modal.dialog.remove, "btn-danger", "");
                 var $removeButton = one.lib.dashlet.button.button(removeButton);
                 footer.push($removeButton);
-                
+
                 var closeButton = one.lib.dashlet.button.single("Cancel", one.f.flows.id.modal.dialog.close, "", "");
                 var $closeButton = one.lib.dashlet.button.button(closeButton);
                 footer.push($closeButton);
-                
+
                 return footer;
             },
             body : function(id) {
@@ -457,12 +461,12 @@ one.f.flows = {
             var h3 = "Add Flow Entry";
             var footer = one.f.flows.modal.footer();
             var $modal = one.lib.modal.spawn(one.f.flows.id.modal.modal, h3, "", footer);
-            
+
             // bind close button
             $('#'+one.f.flows.id.modal.close, $modal).click(function() {
                 $modal.modal('hide');
             });
-            
+
             // bind add flow button
             $('#'+one.f.flows.id.modal.add, $modal).click(function() {
                 one.f.flows.modal.add($modal, 'false');
@@ -472,18 +476,18 @@ one.f.flows = {
             $('#'+one.f.flows.id.modal.install, $modal).click(function() {
                 one.f.flows.modal.add($modal, 'true');
             });
-            
+
             // inject body (nodePorts)
             one.f.flows.modal.ajax.nodes(function(nodes, nodeports) {
                 var $body = one.f.flows.modal.body(nodes, nodeports);
                 one.lib.modal.inject.body($modal, $body);
             });
-            
+
             return $modal;
         },
         add : function($modal, install) {
             var result = {};
-            
+
             result['name'] = $('#'+one.f.flows.id.modal.form.name, $modal).val();
             result['ingressPort'] = $('#'+one.f.flows.id.modal.form.port, $modal).val();
             result['priority'] = $('#'+one.f.flows.id.modal.form.priority, $modal).val();
@@ -505,11 +509,11 @@ one.f.flows = {
                        result['installInHw'] = install;
 
             var nodeId = $('#'+one.f.flows.id.modal.form.nodes, $modal).val();
-            
+
             $.each(result, function(key, value) {
                 if (value == "") delete result[key];
             });
-            
+
             var action = [];
             var $table = $('#'+one.f.flows.id.modal.action.table, $modal);
             $($table.find('tbody').find('tr')).each(function(index, value) {
@@ -518,7 +522,7 @@ one.f.flows = {
                                }
             });
             result['actions'] = action;
-            
+
             // frontend validation
                        if (result['name'] == undefined) {
                                alert('Need flow name');
@@ -532,13 +536,13 @@ one.f.flows = {
                                alert('Please specify an action');
                                return;
                        }
-            
+
                        // package for ajax call
             var resource = {};
             resource['body'] = JSON.stringify(result);
             resource['action'] = 'add';
                        resource['nodeId'] = nodeId;
-            
+
             one.f.flows.modal.ajax.saveflow(resource, function(data) {
                 if (data == "Success") {
                     $modal.modal('hide');
@@ -556,7 +560,7 @@ one.f.flows = {
                     var nodes = one.f.flows.modal.data.nodes(data);
                     var nodeports = data;
                     one.f.flows.registry['nodeports'] = nodeports;
-                    
+
                     successCallback(nodes, nodeports);
                 });
             },
@@ -606,7 +610,7 @@ one.f.flows = {
                        one.lib.form.select.prepend($select, { '' : 'Please Select a Node' });
                        $select.val($select.find("option:first").val());
                        $select.attr('id', one.f.flows.id.modal.form.nodes);
-                       
+
                        // bind onchange
                        $select.change(function() {
                            // retrieve port value
@@ -763,9 +767,9 @@ one.f.flows = {
                 one.f.flows.modal.action.parse(action.attr('value'));
                                $select[0].selectedIndex = 0;
             });
-            
+
                        $fieldset.append($select).append($table);
-            
+
                        // return
                        $form.append($fieldset);
                        return $form;
@@ -1128,11 +1132,11 @@ one.f.flows = {
                 var addButton = one.lib.dashlet.button.single("Add Action", one.f.flows.id.modal.action.add, "btn-primary", "");
                 var $addButton = one.lib.dashlet.button.button(addButton);
                 footer.push($addButton);
-                
+
                 var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.action.close, "", "");
                 var $closeButton = one.lib.dashlet.button.button(closeButton);
                 footer.push($closeButton);
-                
+
                 return footer;
             }
         },
@@ -1142,23 +1146,24 @@ one.f.flows = {
                        var installButton = one.lib.dashlet.button.single("Install Flow", one.f.flows.id.modal.install, "btn-success", "");
                        var $installButton = one.lib.dashlet.button.button(installButton);
                        footer.push($installButton);
-            
+
             var addButton = one.lib.dashlet.button.single("Save Flow", one.f.flows.id.modal.add, "btn-primary", "");
             var $addButton = one.lib.dashlet.button.button(addButton);
             footer.push($addButton);
-            
+
             var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.close, "", "");
             var $closeButton = one.lib.dashlet.button.button(closeButton);
             footer.push($closeButton);
-            
+
             return footer;
         }
     },
     ajax : {
         dashlet : function(callback) {
             $.getJSON(one.f.address.root+one.f.address.flows.main, function(data) {
-                one.f.flows.registry['flows'] = data;
-                var body = one.f.flows.data.dashlet(data);
+                one.f.flows.registry['flows'] = data.flows;
+                one.f.flows.registry['privilege'] = data.privilege;
+                var body = one.f.flows.data.dashlet(data.flows);
                 var $body = one.f.flows.body.dashlet(body, callback);
                 callback($body);
             });
@@ -1178,7 +1183,7 @@ one.f.flows = {
                        tr['type'] = ['warning'];
                 tr['entry'] = entry;
                 tr['id'] = value['nodeId'];
-                
+
                 body.push(tr);
             });
             return body;
@@ -1188,14 +1193,14 @@ one.f.flows = {
         dashlet : function(body, callback) {
             var attributes = ['table-striped', 'table-bordered', 'table-hover', 'table-condensed', 'table-cursor'];
             var $table = one.lib.dashlet.table.table(attributes);
-            
+
             var headers = ['Flow Name', 'Node'];
             var $thead = one.lib.dashlet.table.header(headers);
             $table.append($thead);
-            
+
             var $tbody = one.lib.dashlet.table.body(body);
             $table.append($tbody);
-            
+
             return $table;
         }
     }
index a7f7133cb2a8b634d871f1ef53a550d2b0a1a15d..ab2abe9c9ed136e32d15d5c3f992dde5cd4d9b8e 100644 (file)
@@ -1,43 +1,55 @@
 package org.opendaylight.controller.web;
 
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-
 import org.opendaylight.controller.containermanager.IContainerAuthorization;
-import org.opendaylight.controller.sal.authorization.Resource;
+import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.ServiceHelper;
+import org.opendaylight.controller.usermanager.IUserManager;
 
 public class DaylightWebUtil {
-    private static String defaultName = GlobalConstants.DEFAULT.toString();
 
     /**
-     * Returns the container that this user is authorized to access. If the user is not authorized to the requested
-     * container, then this method will return the default container.
+     * Returns the access privilege the user has on the specified container
      *
-     * @param request - HttpServletRequest object to retrieve username
-     * @param container - requested container
-     * @param bundle - respective bundle
-     * @return container name if cleared, else it will always be 'default'
+     * @param userName
+     *            The user name
+     * @param container
+     *            The container name. If null, the default container will be assumed
+     * @param bundle
+     *            The bundle originating the request
+     * @return The access privilege the user is granted on the container
      */
-    public static String getAuthorizedContainer(HttpServletRequest request, String container, Object bundle) {
-        if (container == null) {
-            return defaultName;
+    public static Privilege getContainerPrivilege(String userName,
+            String container, Object bundle) {
+        // Derive the target resource
+        String resource = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Retrieve the Container Authorization service
+        IContainerAuthorization auth = (IContainerAuthorization) ServiceHelper
+                .getGlobalInstance(IContainerAuthorization.class, bundle);
+        if (auth != null) {
+            return auth.getResourcePrivilege(userName, resource);
         }
 
-        String username = request.getUserPrincipal().getName();
-        IContainerAuthorization containerAuthorization = (IContainerAuthorization)
-                ServiceHelper.getGlobalInstance(IContainerAuthorization.class, bundle);
-        if (containerAuthorization != null) {
-            Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
-            for(Resource resource : resources) {
-                String name = (String) resource.getResource();
-                if(container.equals(name)) {
-                    return name;
+        /*
+         * Container Authorization service not available. We can only derive the
+         * access privilege to the default container based on user level
+         */
+        if (resource.equals(GlobalConstants.DEFAULT.toString())) {
+            IUserManager userManager = (IUserManager) ServiceHelper
+                    .getGlobalInstance(IUserManager.class, bundle);
+            if (userManager != null) {
+                switch (userManager.getUserLevel(userName)) {
+                case NETWORKADMIN:
+                    return Privilege.WRITE;
+                case NETWORKOPERATOR:
+                    return Privilege.READ;
+                default:
+                    return Privilege.NONE;
                 }
             }
         }
-        return defaultName;
+
+        return Privilege.NONE;
     }
 }
\ No newline at end of file
index 62b64a51849ea2ee08c4b9f43cffca8439bd5cad..31d743ee2308712d2b5df3d174b7e8ebdb89748c 100644 (file)
@@ -25,12 +25,11 @@ import java.util.Set;
 import javax.servlet.http.HttpServletRequest;
 
 import org.opendaylight.controller.configuration.IConfigurationAware;
-import org.opendaylight.controller.containermanager.IContainerAuthorization;
-import org.opendaylight.controller.sal.authorization.Resource;
-import org.opendaylight.controller.sal.authorization.UserLevel;
+import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Bandwidth;
 import org.opendaylight.controller.sal.core.Edge;
 import org.opendaylight.controller.sal.core.Host;
+import org.opendaylight.controller.sal.core.Name;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.Node.NodeIDType;
 import org.opendaylight.controller.sal.core.NodeConnector;
@@ -47,9 +46,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.switchmanager.Switch;
 import org.opendaylight.controller.switchmanager.SwitchConfig;
 import org.opendaylight.controller.topologymanager.ITopologyManager;
-import org.opendaylight.controller.usermanager.IUserManager;
 import org.opendaylight.controller.web.DaylightWebUtil;
-import org.opendaylight.controller.web.IDaylightWeb;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -92,7 +89,15 @@ public class Topology implements IObjectReader, IConfigurationAware {
     @RequestMapping(value = "/visual.json", method = RequestMethod.GET)
     @ResponseBody
     public Collection<Map<String, Object>> getLinkData(@RequestParam(required = false) String container, HttpServletRequest request) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+        if (privilege == Privilege.NONE) {
+            return null;
+        }
 
         ITopologyManager topologyManager = (ITopologyManager) ServiceHelper
                 .getInstance(ITopologyManager.class, containerName, this);
@@ -191,7 +196,14 @@ public class Topology implements IObjectReader, IConfigurationAware {
                         break;
                     }
                 }
-                EdgeBean edge = new EdgeBean(link, bandwidth);
+                NodeConnector headNodeConnector = link.getHeadNodeConnector();
+                NodeConnector tailNodeConnector = link.getTailNodeConnector();
+
+                String headDescription = this.getNodeConnectorDescription(headNodeConnector, switchManager);
+                String tailDescription = this.getNodeConnectorDescription(tailNodeConnector, switchManager);
+                String headPortDescription = this.getNodeConnectorPortDescription(headNodeConnector, switchManager);
+                String tailPortDescription = this.getNodeConnectorPortDescription(tailNodeConnector, switchManager);
+                EdgeBean edge = new EdgeBean(link, bandwidth, headDescription, tailDescription, headPortDescription, tailPortDescription);
                 adjacencies.add(edge.out());
             }
 
@@ -254,11 +266,32 @@ public class Topology implements IObjectReader, IConfigurationAware {
     }
 
     protected NodeBean createNodeBean(String description, Node node) {
+        String name = this.getDescription(description, node);
+        return  new NodeBean(node.toString(), name, NodeType.NODE);
+    }
+
+    private String getDescription(String description, Node node) {
         String name = (description == null ||
-                        description.trim().isEmpty() ||
-                        description.equalsIgnoreCase("none"))?
-                                        node.toString() : description;
-                return  new NodeBean(node.toString(), name, NodeType.NODE);
+                description.trim().isEmpty() ||
+                description.equalsIgnoreCase("none"))?
+                                node.toString() : description;
+        return name;
+    }
+
+    private String getNodeConnectorDescription(NodeConnector nodeConnector, ISwitchManager switchManager) {
+        Node node = nodeConnector.getNode();
+        String description = switchManager.getNodeDescription(node);
+        String name = this.getDescription(description, node);
+        return name;
+    }
+
+    private String getNodeConnectorPortDescription(NodeConnector nodeConnector, ISwitchManager switchManager) {
+        Name ncName = (Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName);
+        String nodeConnectorName = nodeConnector.getNodeConnectorIDString();
+        if (ncName != null) {
+            nodeConnectorName = ncName.getValue();
+        }
+        return nodeConnectorName;
     }
 
     @SuppressWarnings("unchecked")
@@ -384,11 +417,15 @@ public class Topology implements IObjectReader, IConfigurationAware {
     public Map<String, Object> post(@PathVariable String nodeId, @RequestParam(required = true) String x,
                 @RequestParam(required = true) String y, @RequestParam(required = false) String container,
                 HttpServletRequest request) {
-        if (!authorize(UserLevel.NETWORKADMIN, request)) {
-                return new HashMap<String, Object>(); // silently disregard new node position
-        }
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
 
-        String containerName = getAuthorizedContainer(request, container);
+        if (privilege != Privilege.WRITE) {
+            return new HashMap<String, Object>(); // silently disregard new node position
+        }
 
         String id = new String(nodeId);
 
@@ -465,36 +502,47 @@ public class Topology implements IObjectReader, IConfigurationAware {
                 data = new HashMap<String, String>();
         }
 
-        public EdgeBean(Edge link, Bandwidth bandwidth) {
-                this();
-                this.source = link.getHeadNodeConnector();
-                this.destination = link.getTailNodeConnector();
-
-                // data
-                data.put("$bandwidth", bandwidth.toString());
-                data.put("$color", bandwidthColor(bandwidth));
-                data.put("$nodeToPort", destination.getID().toString());
-                data.put("$nodeFromPort", source.getID().toString());
-                data.put("$descFrom", source.getNode().toString());
-                data.put("$descTo", destination.getNode().toString());
-                data.put("$nodeFromPortName", source.toString());
-                data.put("$nodeToPortName", destination.toString());
+        /**
+         * EdgeBean object that includes complete node description
+         *
+         * @param link
+         * @param bandwidth
+         * @param headDescription
+         * @param tailDescription
+         */
+        public EdgeBean(Edge link, Bandwidth bandwidth, String headDescription,
+                String tailDescription, String headPortDescription, String tailPortDescription) {
+            this();
+            this.source = link.getHeadNodeConnector();
+            this.destination = link.getTailNodeConnector();
+
+            // data
+            data.put("$bandwidth", bandwidth.toString());
+            data.put("$color", bandwidthColor(bandwidth));
+            data.put("$nodeToPort", destination.getID().toString());
+            data.put("$nodeFromPort", source.getID().toString());
+            data.put("$descFrom", headDescription);
+            data.put("$descTo", tailDescription);
+            data.put("$nodeFromPortName", source.toString());
+            data.put("$nodeToPortName", destination.toString());
+            data.put("$nodeFromPortDescription", headPortDescription);
+            data.put("$nodeToPortDescription", tailPortDescription);
         }
 
         public EdgeBean(NodeConnector connector, Long hostId) {
-                this();
-                this.source = null;
-                this.destination = connector;
-                this.hostId = hostId;
-
-                data.put("$bandwidth", "N/A");
-                data.put("$color", bandwidthColor(new Bandwidth(0)));
-                data.put("$nodeToPort", connector.getNodeConnectorIDString());
-                data.put("$nodeFromPort", connector.getNodeConnectorIDString());
-                data.put("$descTo", "");
-                data.put("$descFrom", "");
-                data.put("$nodeToPortName", "");
-                data.put("$nodeFromPortName", "");
+            this();
+            this.source = null;
+            this.destination = connector;
+            this.hostId = hostId;
+
+            data.put("$bandwidth", "N/A");
+            data.put("$color", bandwidthColor(new Bandwidth(0)));
+            data.put("$nodeToPort", connector.getNodeConnectorIDString());
+            data.put("$nodeFromPort", connector.getNodeConnectorIDString());
+            data.put("$descTo", "");
+            data.put("$descFrom", "");
+            data.put("$nodeToPortName", "");
+            data.put("$nodeFromPortName", "");
         }
 
         public Map<String, Object> out() {
@@ -539,51 +587,13 @@ public class Topology implements IObjectReader, IConfigurationAware {
         public static final String HOST = "host";
     }
 
-    private boolean authorize(UserLevel level, HttpServletRequest request) {
-        IUserManager userManager = (IUserManager) ServiceHelper
-                .getGlobalInstance(IUserManager.class, this);
-        if (userManager == null) {
-                return false;
-        }
-
-        String username = request.getUserPrincipal().getName();
-        UserLevel userLevel = userManager.getUserLevel(username);
-        if (userLevel.toNumber() <= level.toNumber()) {
-                return true;
-        }
-        return false;
-    }
-
-    private String getAuthorizedContainer(HttpServletRequest request, String container) {
-        String username = request.getUserPrincipal().getName();
-        IContainerAuthorization containerAuthorization = (IContainerAuthorization) ServiceHelper.
-                        getGlobalInstance(IContainerAuthorization.class, this);
-        if (containerAuthorization != null) {
-                Set<Resource> resources = containerAuthorization.getAllResourcesforUser(username);
-                if (authorizeContainer(container, resources)) {
-                        return container;
-                }
-        }
-
-        return GlobalConstants.DEFAULT.toString();
-    }
-
-    private boolean authorizeContainer(String container, Set<Resource> resources) {
-        for(Resource resource : resources) {
-                String containerName = (String) resource.getResource();
-                if (containerName.equals(container)) {
-                        return true;
-                }
-        }
-
-        return false;
-    }
-
     @SuppressWarnings("unchecked")
         private void loadConfiguration() {
         ObjectReader objReader = new ObjectReader();
         metaCache = (Map<String, Map<String, Map<String, Object>>>) objReader.read(this, topologyWebFileName);
-        if (metaCache == null) metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
+        if (metaCache == null) {
+            metaCache = new HashMap<String, Map<String, Map<String, Object>>>();
+        }
     }
 
     @Override
index bde4152f5bdfd59c3631a5a80fbaccfd5011343a..f5fda3d1bc8fe245323d3cb8666a185e9753472a 100644 (file)
@@ -14,6 +14,7 @@ import java.util.Arrays;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 import javax.servlet.http.HttpServletRequest;
@@ -21,6 +22,7 @@ import javax.servlet.http.HttpServletRequest;
 import org.opendaylight.controller.sal.action.Action;
 import org.opendaylight.controller.sal.action.Output;
 import org.opendaylight.controller.sal.action.SetVlanId;
+import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.authorization.UserLevel;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
@@ -50,10 +52,22 @@ import org.springframework.web.bind.annotation.ResponseBody;
 @RequestMapping("/")
 public class Troubleshoot implements IDaylightWeb {
     private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER;
+    private static final List<String> flowStatsColumnNames = Arrays.asList("Node", "In Port",
+            "DL Src", "DL Dst", "DL Type", "DL Vlan", "NW Src", "NW Dst",
+            "NW Proto", "TP Src", "TP Dst", "Actions", "Bytes", "Packets",
+            "Time (s)", "Timeout (s)", "Out Port(s)", "Out Vlan",
+            "Priority");
+    private static final List<String> portStatsColumnNames = Arrays.asList("Node Connector",
+            "Rx Pkts", "Tx Pkts", "Rx Bytes", "Tx Bytes", "Rx Drops",
+            "Tx Drops", "Rx Errs", "Tx Errs", "Rx Frame Errs",
+            "Rx OverRun Errs", "Rx CRC Errs", "Collisions");
+    private static final List<String> nodesColumnNames = Arrays.asList("Node", "Node ID", "Statistics");
+    private static final List<String> nodeStatsColumnNames = Arrays.asList("Node", "Node ID", "Statistics");
     private final String WEB_NAME = "Troubleshoot";
     private final String WEB_ID = "troubleshoot";
     private final short WEB_ORDER = 4;
 
+
     public Troubleshoot() {
         ServiceHelper.registerGlobalService(IDaylightWeb.class, this, null);
     }
@@ -81,30 +95,29 @@ public class Troubleshoot implements IDaylightWeb {
     @RequestMapping(value = "/existingNodes", method = RequestMethod.GET)
     @ResponseBody
     public TroubleshootingJsonBean getExistingNodes(HttpServletRequest request, @RequestParam(required = false) String container) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
-        List<HashMap<String, String>> lines = new ArrayList<HashMap<String, String>>();
-        Set<Node> nodeSet = null;
-        if (switchManager != null) {
-            nodeSet = switchManager.getNodes();
-        }
-        if (nodeSet != null) {
-            for (Node node : nodeSet) {
-                HashMap<String, String> device = new HashMap<String, String>();
-                device.put("nodeName", switchManager.getNodeDescription(node));
-                device.put("nodeId", node.toString());
-                lines.add(device);
+        List<Map<String, String>> lines = new ArrayList<Map<String, String>>();
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+        if (privilege != Privilege.NONE) {
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                    .getInstance(ISwitchManager.class, containerName, this);
+            Set<Node> nodeSet = (switchManager != null) ? switchManager.getNodes() : null;
+            if (nodeSet != null) {
+                for (Node node : nodeSet) {
+                    Map<String, String> device = new HashMap<String, String>();
+                    device.put("nodeName", switchManager.getNodeDescription(node));
+                    device.put("nodeId", node.toString());
+                    lines.add(device);
+                }
             }
         }
-        TroubleshootingJsonBean result = new TroubleshootingJsonBean();
 
-        List<String> guiFieldNames = new ArrayList<String>();
-        guiFieldNames.add("Node");
-        guiFieldNames.add("Node ID");
-        guiFieldNames.add("Statistics");
-
-        result.setColumnNames(guiFieldNames);
+        TroubleshootingJsonBean result = new TroubleshootingJsonBean();
+        result.setColumnNames(nodesColumnNames);
         result.setNodeData(lines);
         return result;
     }
@@ -112,35 +125,34 @@ public class Troubleshoot implements IDaylightWeb {
     @RequestMapping(value = "/uptime", method = RequestMethod.GET)
     @ResponseBody
     public TroubleshootingJsonBean getUptime(HttpServletRequest request, @RequestParam(required = false) String container) {
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        ISwitchManager switchManager = (ISwitchManager) ServiceHelper
-                .getInstance(ISwitchManager.class, containerName, this);
-        List<HashMap<String, String>> lines = new ArrayList<HashMap<String, String>>();
-        Set<Node> nodeSet = null;
-        if (switchManager != null) {
-            nodeSet = switchManager.getNodes();
-        }
-        if (nodeSet != null) {
-            for (Node node : nodeSet) {
-                HashMap<String, String> device = new HashMap<String, String>();
-                device.put("nodeName", switchManager.getNodeDescription(node));
-                device.put("nodeId", node.toString());
-                TimeStamp timeStamp = (TimeStamp) switchManager.getNodeProp(
-                        node, TimeStamp.TimeStampPropName);
-                Long time = (timeStamp == null) ? 0 : timeStamp.getValue();
-                String date = (time == 0) ? "" : (new Date(time)).toString();
-                device.put("connectedSince", date);
-                lines.add(device);
+        List<Map<String, String>> lines = new ArrayList<Map<String, String>>();
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+        if (privilege != Privilege.NONE) {
+            ISwitchManager switchManager = (ISwitchManager) ServiceHelper
+                    .getInstance(ISwitchManager.class, containerName, this);
+            Set<Node> nodeSet = (switchManager != null) ? switchManager.getNodes() : null;
+            if (nodeSet != null) {
+                for (Node node : nodeSet) {
+                    Map<String, String> device = new HashMap<String, String>();
+                    device.put("nodeName", switchManager.getNodeDescription(node));
+                    device.put("nodeId", node.toString());
+                    TimeStamp timeStamp = (TimeStamp) switchManager.getNodeProp(
+                            node, TimeStamp.TimeStampPropName);
+                    Long time = (timeStamp == null) ? 0 : timeStamp.getValue();
+                    String date = (time == 0) ? "" : (new Date(time)).toString();
+                    device.put("connectedSince", date);
+                    lines.add(device);
+                }
             }
         }
-        TroubleshootingJsonBean result = new TroubleshootingJsonBean();
 
-        List<String> guiFieldNames = new ArrayList<String>();
-        guiFieldNames.add("Node");
-        guiFieldNames.add("Node ID");
-        guiFieldNames.add("Connected");
-
-        result.setColumnNames(guiFieldNames);
+        TroubleshootingJsonBean result = new TroubleshootingJsonBean();
+        result.setColumnNames(nodeStatsColumnNames);
         result.setNodeData(lines);
         return result;
     }
@@ -150,24 +162,27 @@ public class Troubleshoot implements IDaylightWeb {
     public TroubleshootingJsonBean getFlowStats(
             @RequestParam("nodeId") String nodeId,
             HttpServletRequest request, @RequestParam(required = false) String container) {
-        Node node = Node.fromString(nodeId);
-        List<HashMap<String, String>> cells = new ArrayList<HashMap<String, String>>();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
-                .getInstance(IStatisticsManager.class, containerName, this);
-
-        List<FlowOnNode> statistics = statisticsManager.getFlows(node);
-        for (FlowOnNode stats : statistics) {
-            cells.add(this.convertFlowStatistics(node, stats, containerName));
+        List<Map<String, String>> cells = new ArrayList<Map<String, String>>();
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+        if (privilege != Privilege.NONE) {
+            IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
+                    .getInstance(IStatisticsManager.class, containerName, this);
+            if (statisticsManager != null) {
+                Node node = Node.fromString(nodeId);
+                List<FlowOnNode> statistics = statisticsManager.getFlows(node);
+                for (FlowOnNode stats : statistics) {
+                    cells.add(this.convertFlowStatistics(node, stats, containerName));
+                }
+            }
         }
-        List<String> columnNames = new ArrayList<String>();
-        columnNames.addAll(Arrays.asList(new String[] { "Node", "In Port",
-                "DL Src", "DL Dst", "DL Type", "DL Vlan", "NW Src", "NW Dst",
-                "NW Proto", "TP Src", "TP Dst", "Actions", "Bytes", "Packets",
-                "Time (s)", "Timeout (s)", "Out Port(s)", "Out Vlan",
-                "Priority" }));
+
         TroubleshootingJsonBean result = new TroubleshootingJsonBean();
-        result.setColumnNames(columnNames);
+        result.setColumnNames(flowStatsColumnNames);
         result.setNodeData(cells);
         return result;
     }
@@ -177,30 +192,35 @@ public class Troubleshoot implements IDaylightWeb {
     public TroubleshootingJsonBean getPortStats(
             @RequestParam("nodeId") String nodeId,
             HttpServletRequest request, @RequestParam(required = false) String container) {
-        Node node = Node.fromString(nodeId);
-        List<HashMap<String, String>> cells = new ArrayList<HashMap<String, String>>();
-        String containerName = DaylightWebUtil.getAuthorizedContainer(request, container, this);
-        IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
-                .getInstance(IStatisticsManager.class, containerName, this);
-        List<NodeConnectorStatistics> statistics = statisticsManager
-                .getNodeConnectorStatistics(node);
-        for (NodeConnectorStatistics stats : statistics) {
-            cells.add(this.convertPortsStatistics(stats));
+        List<Map<String, String>> cells = new ArrayList<Map<String, String>>();
+        String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container;
+
+        // Derive the privilege this user has on the current container
+        String userName = request.getUserPrincipal().getName();
+        Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this);
+
+        if (privilege != Privilege.NONE) {
+            IStatisticsManager statisticsManager = (IStatisticsManager) ServiceHelper
+                    .getInstance(IStatisticsManager.class, containerName, this);
+            if (statisticsManager != null) {
+                Node node = Node.fromString(nodeId);
+                List<NodeConnectorStatistics> statistics = statisticsManager
+                        .getNodeConnectorStatistics(node);
+                for (NodeConnectorStatistics stats : statistics) {
+                    cells.add(this.convertPortsStatistics(stats));
+                }
+            }
         }
+
         TroubleshootingJsonBean result = new TroubleshootingJsonBean();
-        List<String> columnNames = new ArrayList<String>();
-        columnNames.addAll(Arrays.asList(new String[] { "Node Connector",
-                "Rx Pkts", "Tx Pkts", "Rx Bytes", "Tx Bytes", "Rx Drops",
-                "Tx Drops", "Rx Errs", "Tx Errs", "Rx Frame Errs",
-                "Rx OverRun Errs", "Rx CRC Errs", "Collisions" }));
-        result.setColumnNames(columnNames);
+        result.setColumnNames(portStatsColumnNames);
         result.setNodeData(cells);
         return result;
     }
 
-    private HashMap<String, String> convertPortsStatistics(
+    private Map<String, String> convertPortsStatistics(
             NodeConnectorStatistics ncStats) {
-        HashMap<String, String> row = new HashMap<String, String>();
+        Map<String, String> row = new HashMap<String, String>();
 
         row.put("nodeConnector",
                 String.valueOf(ncStats.getNodeConnector().toString()));
@@ -223,10 +243,10 @@ public class Troubleshoot implements IDaylightWeb {
         return row;
     }
 
-    private HashMap<String, String> convertFlowStatistics(Node node,
+    private Map<String, String> convertFlowStatistics(Node node,
             FlowOnNode flowOnNode,
             String containerName) {
-        HashMap<String, String> row = new HashMap<String, String>();
+        Map<String, String> row = new HashMap<String, String>();
         Flow flow = flowOnNode.getFlow();
         Match match = flow.getMatch();
         ISwitchManager switchManager = (ISwitchManager) ServiceHelper
index 1030c49511b0be53a6c48d25a178f28b77fde039..3c9a8b0b266be9174e4c848c2dcc20ecb6591d90 100644 (file)
@@ -9,12 +9,12 @@
 
 package org.opendaylight.controller.troubleshoot.web;
 
-import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 public class TroubleshootingJsonBean {
     private List<String> columnNames;
-    private List<HashMap<String, String>> nodeData;
+    private List<Map<String, String>> nodeData;
 
     public List<String> getColumnNames() {
         return columnNames;
@@ -24,11 +24,11 @@ public class TroubleshootingJsonBean {
         this.columnNames = columnNames;
     }
 
-    public List<HashMap<String, String>> getNodeData() {
+    public List<Map<String, String>> getNodeData() {
         return nodeData;
     }
 
-    public void setNodeData(List<HashMap<String, String>> nodeData) {
+    public void setNodeData(List<Map<String, String>> nodeData) {
         this.nodeData = nodeData;
     }
 }