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
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);
+ }
}
}
// 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])
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;
--- /dev/null
+/*
+ * 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;
+ }
+
+}
--- /dev/null
+/*
+ * 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);
+ }
+}
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()) {
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()) {
.addProperty(parseToClassName(leafName));
propBuilder.setReadOnly(isReadOnly);
- propBuilder.addReturnType(returnType);
- propBuilder.addComment(leafDesc);
+ propBuilder.setReturnType(returnType);
+ propBuilder.setComment(leafDesc);
toBuilder.addEqualsIdentity(propBuilder);
toBuilder.addHashIdentity(propBuilder);
final MethodSignatureBuilder getMethod = interfaceBuilder
.addMethod(getterMethodName(schemaNodeName));
- getMethod.addComment(comment);
- getMethod.addReturnType(returnType);
+ getMethod.setComment(comment);
+ getMethod.setReturnType(returnType);
return getMethod;
}
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;
}
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;
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);
}
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) {
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());
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");
}
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();
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
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) {
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();
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);
}
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) {
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(
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);
}
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) {
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) {
final List<ExtendedType> extUnions = UnionDependencySort
.sort(typeDefinitions);
for (final ExtendedType extUnionType : extUnions) {
- addUnionGeneratedTypeDefinition(basePackageName, extUnionType);
+ addUnionGeneratedTypeDefinition(basePackageName,
+ extUnionType);
}
}
}
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)
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);
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);
}
final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
.addProperty(propertyName);
- genPropBuilder.addReturnType(javaType);
+ genPropBuilder.setReturnType(javaType);
genTOBuilder.addEqualsIdentity(genPropBuilder);
genTOBuilder.addHashIdentity(genPropBuilder);
genTOBuilder.addToStringProperty(genPropBuilder);
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) {
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,
}
}
} else if (unionType instanceof EnumTypeDefinition) {
- final EnumBuilder
- enumBuilder = resolveInnerEnumFromTypeDefinition(
+ final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(
(EnumTypeDefinition) unionType, typeName,
unionGenTransObject);
final Type enumRefType = new ReferencedTypeImpl(
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)) {
}
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();
+ }
}
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 " +
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;
--- /dev/null
+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
--- /dev/null
+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
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
}\r
return "Type (" + packageName + "." + name + ")";\r
}\r
-\r
}\r
*/
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();
}
--- /dev/null
+/*
+ * 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();
+ }
+}
--- /dev/null
+/*
+ * 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;
+ }
+}
--- /dev/null
+/*
+ * 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();
+ }
+}
--- /dev/null
+/*
+ * 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();
+ }
+}
+/*
+ * 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;
super();
this.packageName = packageName;
this.name = name;
-
- annotationBuilders = new ArrayList<AnnotationTypeBuilder>();
- parameters = new ArrayList<AnnotationType.Parameter>();
+ annotationBuilders = new ArrayList<>();
+ parameters = new ArrayList<>();
}
@Override
return name;
}
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) {
if (packageName != null && name != null) {
this.packageName = packageName;
this.name = name;
- this.annotations = new ArrayList<AnnotationType>();
+ this.annotations = new ArrayList<>();
for (final AnnotationTypeBuilder builder : annotationBuilders) {
annotations.add(builder.toInstance());
}
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());
}
return name;
}
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public List<AnnotationType> getAnnotations() {
return annotations;
+++ /dev/null
-/*
- * 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();
- }
- }
-}
--- /dev/null
+/*
+ * 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();
+ }
+}
super();
this.packageName = packageName;
this.name = name;
- values = new ArrayList<Enumeration.Pair>();
+ values = new ArrayList<>();
}
@Override
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) {
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,
return name;
}
+ @Override
+ public String getFullyQualifiedName() {
+ return packageName + "." + name;
+ }
+
@Override
public List<Pair> getValues() {
return values;
--- /dev/null
+/*
+ * 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
--- /dev/null
+/*
+ * 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();
+ }
+}
*/
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;
}
@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
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;
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=");
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);
- }
- }
}
*/
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);
}
}
}
+/*
+ * 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
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;
}
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) {
} 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;
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
--- /dev/null
+/*
+ * 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();
+ }
+}
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;
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");
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");
@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;
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);
writer.write(NL);
writer.write(GeneratorUtil.createClassDeclaration(genTO, "",
- imports, isIdentity));
+ imports, genTO.isAbstract()));
writer.write(NL);
writer.write(NL);
}
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,
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
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()));
}
return writer;
}
-
}
"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();
"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();
*/\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
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();
}
}
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
*/
package org.opendaylight.controller.sal.binding.model.api;
+/**
+ * The Concrete Type is marker interface that encapsulates definition of java
+ * concrete type.
+ */
public interface ConcreteType extends Type {
}
*/\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
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();
*/\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
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();
}
* <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>
* 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();
-
}
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();
}
}
\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
*/\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
* @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
--- /dev/null
+/*
+ * 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();
+}
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();
}
import org.opendaylight.controller.sal.binding.model.api.Type;\r
\r
/**\r
-\r
*\r
*/\r
public interface ConstantBuilder {\r
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);
}
*/
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);
}
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();
-
}
*/
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();
}
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);
}
--- /dev/null
+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);
+}
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 {
this.defaultCase = defaultCase;
}
-
private final class ChoiceNodeImpl implements ChoiceNode {
private final QName qname;
private SchemaPath path;
return augmentations;
}
- private void setAvailableAugmentations(
- Set<AugmentationSchema> availableAugmentations) {
+ private void setAvailableAugmentations(Set<AugmentationSchema> availableAugmentations) {
if (availableAugmentations != null) {
this.augmentations = availableAugmentations;
}
return unknownNodes;
}
- private void setUnknownSchemaNodes(
- List<UnknownSchemaNode> unknownSchemaNodes) {
+ private void setUnknownSchemaNodes(List<UnknownSchemaNode> unknownSchemaNodes) {
if (unknownSchemaNodes != null) {
this.unknownNodes = unknownSchemaNodes;
}
}
}
+ @Override
public String getDefaultCase() {
return defaultCase;
}
@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("]");
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;
@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);
@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);
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) {
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;
}
@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;
}
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.
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>();
}
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);
}
// 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);
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);
* @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);
}
}
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) {
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);
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());
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) {
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());
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);
* 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) {
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();
}
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;
* @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());
}
}
* @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());
}
// 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);
* @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);
}
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;
}
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;
}
}
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();
}
* @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) {
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);
}
}
* @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();
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) {
}
}
- 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];
}
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();
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;
* @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;
}
* @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) {
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);
}
}
}
* 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;
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;
}
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
}
@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);
}
}
}
} catch (ParseException e) {
- final String message = "Failed to parse revision string: "
- + revisionDateStr;
+ final String message = "Failed to parse revision string: " + revisionDateStr;
logger.warn(message);
}
}
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);
}
}
}
@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);
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;
@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));
}
// 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);
typeQName = new QName(null, null, prefix, name);
}
} else {
- typeQName = new QName(namespace, revision, yangModelPrefix,
- typeName);
+ typeQName = new QName(namespace, revision, yangModelPrefix, typeName);
}
return typeQName;
}
@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);
}
@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());
@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());
@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
@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());
@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());
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);
}
}
@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());
}
@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());
@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());
}
@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);
}
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;
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);
}
@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);
}
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());
}
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());
}
@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);
}
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);
@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++) {
* 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();
}
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;
}
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;
}
}
public List<LengthConstraint> getLength() {
- if (lengths.isEmpty()) {
+ if (lengths.size() < 2) {
return Collections.emptyList();
}
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;
}
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;
}
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 + ").");
+ }
+ }
+ }
+
}
@Override
public String toString() {
- return UnknownBoundaryNumber.class.getSimpleName() + "[" + value + "]";
+ return value;
}
}
public final class YangModelBuilderUtil {
- private static final Logger logger = LoggerFactory
- .getLogger(YangModelBuilderUtil.class);
+ private static final Logger logger = LoggerFactory.getLogger(YangModelBuilderUtil.class);
private 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("\"", "");
}
* @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) {
* @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;
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);
}
* 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(" ");
* @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++) {
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();
}
* @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;
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;
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;
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;
@Override
public String toString() {
- return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name="
- + name + ", value=" + value + "]";
+ return EnumTypeDefinition.EnumPair.class.getSimpleName() + "[name=" + name + ", value=" + value + "]";
}
}
* 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);
* 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;
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);
}
* 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);
* 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;
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);
}
* @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);
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;
* 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++) {
* 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++) {
}
}
String pattern = patternStringFromNode(ctx);
- return BaseConstraints.patternConstraint(pattern, description,
- reference);
+ return BaseConstraints.patternConstraint(pattern, description, reference);
}
/**
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));
}
}
}
* 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);
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);
}
}
}
* @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);
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();
* @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;
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);
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);
}
/**
* 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();
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);
* 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;
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()) {
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);
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());
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());
* 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);
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) {
}
}
- MustDefinition must = new MustDefinitionImpl(mustText.toString(),
- description, reference, errorAppTag, errorMessage);
+ MustDefinition must = new MustDefinitionImpl(mustText.toString(), description, reference, errorAppTag,
+ errorMessage);
return must;
}
* @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) {
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);
}
}
}
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);
}
}
}
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);
}
}
* 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'.");
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'.");
*/
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) {
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);
}
}
}
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) {
}
}
- 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) {
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);
}
}
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) {
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) {
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) {
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) {
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);
}
}
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) {
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);
}
}
@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"));
}
}
@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."));
}
}
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'."));
}
}
@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>"));
+ }
+
+ }
+
}
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;
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());
assertEquals(0, interfaces.getGroupings().size());
assertEquals(0, interfaces.getUses().size());
- ListSchemaNode ifEntry = (ListSchemaNode) interfaces
- .getDataChildByName("ifEntry");
+ ListSchemaNode ifEntry = (ListSchemaNode) interfaces.getDataChildByName("ifEntry");
assertNotNull(ifEntry);
}
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());
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
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);
}
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();
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();
// 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())) {
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;
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());
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());
}
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());
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());
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());
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());
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());
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;
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());
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());
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);
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());
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());
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());
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();
// 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);
@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());
@Test
public void testAnyXml() {
Module testModule = TestUtils.findModule(modules, "types1");
- AnyXmlSchemaNode data = (AnyXmlSchemaNode) testModule
- .getDataChildByName("data");
+ AnyXmlSchemaNode data = (AnyXmlSchemaNode) testModule.getDataChildByName("data");
assertNotNull(data);
}
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());
}
@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);
@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());
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());
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);
}
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();
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);
}
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");
// 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());
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");
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());
leaf testleaf {
type data:my-type1 {
- range "min..max";
+ range "12..max";
}
}
leaf my-type {
type data:my-type1;
}
+ container schemas {
+ }
}
container mycont {
typedef my-string-type {
type my-custom-string {
- length "5..10";
+ length "6..10";
}
}
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 {
--- /dev/null
+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";
+ }
+ }
+
+}
--- /dev/null
+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";
+ }
+ }
+
+}
* @return ChoiceCaseNode objects defined in this node
*/
Set<ChoiceCaseNode> getCases();
+
+ String getDefaultCase();
}
* 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>
* <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;
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"));
}
* @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;
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;
}
*
*/
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;
}
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;
}
builder.append("]");
return builder.toString();
}
+
}
/**
* 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;
}
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;
}
builder.append("]");
return builder.toString();
}
+
}
*
*/
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;
}
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;
}
builder.append("]");
return builder.toString();
}
+
}
/*
- * 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;
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() {
/*
* (non-Javadoc)
*
- * @see org.opendaylight.controller.yang.model.api.TypeDefinition#getDefaultValue()
+ * @see
+ * org.opendaylight.controller.yang.model.api.TypeDefinition#getDefaultValue
+ * ()
*/
@Override
public Object getDefaultValue() {
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;
}
builder.append("]");
return builder.toString();
}
+
}
* 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;
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;
* 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;
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 {
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;
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;
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;
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;
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;
@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();
DevicesJsonBean result = new DevicesJsonBean();
result.setNodeData(nodeData);
+ result.setPrivilege(privilege);
List<String> columnNames = new ArrayList<String>();
columnNames.add("Node ID");
columnNames.add("Node Name");
@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);
@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);
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;
@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,
@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,
@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;
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);
@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);
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);
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);
@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;
@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) {
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,
port.put((Short) nodeConnector.getID(), nodeConnectorName
+ "(" + nodeConnector.getID() + ")");
}
+ }
nodes.put(node.getNode().toString(), port);
}
@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);
@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("###");
: 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);
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;
public void setNodeData(List<Map<String, String>> nodeData) {
this.nodeData = nodeData;
}
+
+ public void setPrivilege(Privilege privilege) {
+ this.privilege = privilege;
+ }
+
+ public Privilege getPrivilege() {
+ return privilege;
+ }
}
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.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();
});
$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;
},
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() {
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"]);
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," ");
},
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;
}
},
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," ");
},
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;
}
},
},
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," ");
},
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;
}
},
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;
@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
// 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);
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);
@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);
@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) {
@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) {
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());
- }
-
}
-/*
- * 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
*/
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
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;
}
}
dashlet : function($dashlet, details) {
var $h4 = one.lib.dashlet.header("Flow Details");
$dashlet.append($h4);
-
+
// details
if (details == undefined) {
var $none = $(document.createElement('div'));
var $p = $(document.createElement('p'));
$p.text('Please select a flow');
$p.addClass('text-center').addClass('text-info');
-
+
$dashlet.append($none)
.append($p);
}
},
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
$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();
$detailDashlet.empty();
var $h4 = one.lib.dashlet.header("Flow Overview");
$detailDashlet.append($h4);
-
+
// details
var flows = one.f.flows.registry.flows;
var flow;
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);
}
});
});
+
+ $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);
},
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) {
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');
$('#'+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();
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) {
}
});
result['actions'] = action;
-
+
// frontend validation
if (result['name'] == undefined) {
alert('Need flow name');
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');
var nodes = one.f.flows.modal.data.nodes(data);
var nodeports = data;
one.f.flows.registry['nodeports'] = nodeports;
-
+
successCallback(nodes, nodeports);
});
},
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
one.f.flows.modal.action.parse(action.attr('value'));
$select[0].selectedIndex = 0;
});
-
+
$fieldset.append($select).append($table);
-
+
// return
$form.append($fieldset);
return $form;
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;
}
},
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);
});
tr['type'] = ['warning'];
tr['entry'] = entry;
tr['id'] = value['nodeId'];
-
+
body.push(tr);
});
return body;
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;
}
}
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
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;
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;
@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);
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());
}
}
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")
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);
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() {
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
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;
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;
@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);
}
@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;
}
@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;
}
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;
}
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()));
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
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;
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;
}
}