Bug 611 - BGP Update message serialization
[bgpcep.git] / bgp / parser-impl / src / main / java / org / opendaylight / protocol / bgp / parser / impl / message / update / CommunitiesAttributeParser.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.bgp.parser.impl.message.update;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Lists;
12
13 import io.netty.buffer.ByteBuf;
14
15 import java.util.List;
16
17 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
18 import org.opendaylight.protocol.bgp.parser.spi.AttributeParser;
19 import org.opendaylight.protocol.bgp.parser.spi.AttributeSerializer;
20 import org.opendaylight.protocol.util.ReferenceCache;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.PathAttributes;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Communities;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributesBuilder;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Community;
25 import org.opendaylight.yangtools.yang.binding.DataObject;
26
27 public final class CommunitiesAttributeParser implements AttributeParser, AttributeSerializer {
28
29     public static final int TYPE = 8;
30
31     private final ReferenceCache refCache;
32
33     public CommunitiesAttributeParser(final ReferenceCache refCache) {
34         this.refCache = Preconditions.checkNotNull(refCache);
35     }
36
37     @Override
38     public void parseAttribute(final ByteBuf buffer, final PathAttributesBuilder builder) throws BGPDocumentedException {
39         final List<Communities> set = Lists.newArrayList();
40         while (buffer.isReadable()) {
41             set.add((Communities) CommunitiesParser.parseCommunity(this.refCache, buffer.slice(buffer.readerIndex(),
42                     CommunitiesParser.COMMUNITY_LENGTH)));
43             buffer.skipBytes(CommunitiesParser.COMMUNITY_LENGTH);
44         }
45         builder.setCommunities(set);
46     }
47
48     @Override
49     public void serializeAttribute(DataObject attribute, ByteBuf byteAggregator) {
50         PathAttributes pathAttributes = (PathAttributes) attribute;
51         List<Communities> communities = pathAttributes.getCommunities();
52         if (communities == null) {
53             return;
54         }
55         for (Community community : communities) {
56             byteAggregator.writeInt(community.getAsNumber().getValue().intValue());
57         }
58     }
59 }