Code Clean Up
[bgpcep.git] / pcep / spi / src / main / java / org / opendaylight / protocol / pcep / spi / AbstractMessageParser.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.pcep.spi;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.primitives.UnsignedBytes;
13 import io.netty.buffer.ByteBuf;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.List;
17 import javax.annotation.Nullable;
18 import org.opendaylight.protocol.util.BitArray;
19 import org.opendaylight.protocol.util.ByteArray;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.iana.rev130816.EnterpriseNumber;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.PcerrBuilder;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Object;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.ObjectHeader;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcep.error.object.ErrorObjectBuilder;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.PcerrMessageBuilder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.pcerr.message.ErrorsBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.pcerr.message.error.type.RequestCaseBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.pcerr.message.error.type.request._case.RequestBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.pcerr.message.error.type.request._case.request.RpsBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.rp.object.Rp;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.vendor.information.objects.VendorInformationObject;
33
34 public abstract class AbstractMessageParser implements MessageParser, MessageSerializer {
35
36     private static final int COMMON_OBJECT_HEADER_LENGTH = 4;
37
38     private static final int OT_SF_LENGTH = 4;
39     /*
40      * offsets of fields inside of multi-field in bits
41      */
42     private static final int OT_SF_OFFSET = 0;
43     /*
44      * flags offsets inside multi-filed
45      */
46     private static final int PROCESSED = 6;
47     private static final int IGNORED = 7;
48
49     private final ObjectRegistry registry;
50
51     protected AbstractMessageParser(final ObjectRegistry registry) {
52         this.registry = Preconditions.checkNotNull(registry);
53     }
54
55     /**
56      * Calls registry to pick up specific object serializer for given object.
57      * Checks if the object is not null.
58      * @param object Object to be serialized, may be null
59      * @param buffer ByteBuf where the object should be serialized
60      */
61     protected void serializeObject(@Nullable final Object object, final ByteBuf buffer) {
62         if (object == null) {
63             return;
64         }
65         this.registry.serializeObject(object, buffer);
66     }
67
68     private List<Object> parseObjects(final ByteBuf bytes) throws PCEPDeserializerException {
69         final List<Object> objs = new ArrayList<>();
70         while (bytes.isReadable()) {
71             if (bytes.readableBytes() < COMMON_OBJECT_HEADER_LENGTH) {
72                 throw new PCEPDeserializerException("Too few bytes in passed array. Passed: " + bytes.readableBytes() + " Expected: >= "
73                         + COMMON_OBJECT_HEADER_LENGTH + ".");
74             }
75             final int objClass = bytes.readUnsignedByte();
76
77             final byte flagsByte = bytes.readByte();
78             final BitArray flags = BitArray.valueOf(flagsByte);
79             final int objType = UnsignedBytes.toInt(ByteArray.copyBitsRange(flagsByte, OT_SF_OFFSET, OT_SF_LENGTH));
80             final int objLength = bytes.readUnsignedShort();
81
82             if (bytes.readableBytes() < objLength - COMMON_OBJECT_HEADER_LENGTH) {
83                 throw new PCEPDeserializerException("Too few bytes in passed array. Passed: " + bytes.readableBytes() + " Expected: >= "
84                         + objLength + ".");
85             }
86             // copy bytes for deeper parsing
87             final ByteBuf bytesToPass = bytes.readSlice(objLength - COMMON_OBJECT_HEADER_LENGTH);
88
89             final ObjectHeader header = new ObjectHeaderImpl(flags.get(PROCESSED), flags.get(IGNORED));
90
91             if (VendorInformationUtil.isVendorInformationObject(objClass, objType)) {
92                 final EnterpriseNumber enterpriseNumber = new EnterpriseNumber(bytesToPass.readUnsignedInt());
93                 final Optional<? extends Object> obj = this.registry.parseVendorInformationObject(enterpriseNumber, header, bytesToPass);
94                 if (obj.isPresent()) {
95                     objs.add(obj.get());
96                 }
97             } else {
98                 // parseObject is required to return null for P=0 errored objects
99                 final Object o = this.registry.parseObject(objClass, objType, header, bytesToPass);
100                 if (o != null) {
101                     objs.add(o);
102                 }
103             }
104         }
105
106         return objs;
107     }
108
109     public static Message createErrorMsg(final PCEPErrors e, final Optional<Rp> rp) {
110         final PcerrMessageBuilder msgBuilder = new PcerrMessageBuilder();
111         if (rp.isPresent()) {
112             new RequestCaseBuilder().setRequest(new RequestBuilder().setRps(Collections.singletonList(new RpsBuilder().setRp(
113                     rp.get()).build())).build()).build();
114         }
115         return new PcerrBuilder().setPcerrMessage(
116                 msgBuilder.setErrors(Collections.singletonList(new ErrorsBuilder().setErrorObject(
117                     new ErrorObjectBuilder().setType(e.getErrorType()).setValue(
118                         e.getErrorValue()).build()).build())).build()).build();
119     }
120
121     protected abstract Message validate(final List<Object> objects, final List<Message> errors) throws PCEPDeserializerException;
122
123     @Override
124     public final Message parseMessage(final ByteBuf buffer, final List<Message> errors) throws PCEPDeserializerException {
125         Preconditions.checkNotNull(buffer, "Buffer may not be null");
126
127         // Parse objects first
128         final List<Object> objs = parseObjects(buffer);
129
130         // Run validation
131         return validate(objs, errors);
132     }
133
134     protected final void serializeVendorInformationObjects(final List<VendorInformationObject> viObjects, final ByteBuf buffer) {
135         if (viObjects != null) {
136             for (final VendorInformationObject viObject : viObjects) {
137                 this.registry.serializeVendorInformationObject(viObject, buffer);
138             }
139         }
140     }
141
142     protected final List<VendorInformationObject> addVendorInformationObjects(final List<Object> objects) {
143         final List<VendorInformationObject> vendorInfo = new ArrayList<>();
144         while (!objects.isEmpty() && objects.get(0) instanceof VendorInformationObject) {
145             final VendorInformationObject viObject = (VendorInformationObject) objects.get(0);
146             vendorInfo.add(viObject);
147             objects.remove(0);
148         }
149         return vendorInfo;
150     }
151 }