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