Activate code generation
[bgpcep.git] / framework / src / main / java / org / opendaylight / protocol / framework / ProtocolOutputStream.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.framework;
9
10 import java.nio.ByteBuffer;
11 import java.util.ArrayDeque;
12 import java.util.Queue;
13
14 /**
15  * Data stream interface between ProtocolMessage and byte array,
16  * that represents this message in serialized form. Its instance
17  * needs to be present in protocol specific session, to allow
18  * sending messages from the session via the put() method.
19  */
20 public final class ProtocolOutputStream {
21
22         /**
23          * List of Buffers whose content needs to be written to socket.
24          */
25         private final Queue<ByteBuffer> pendingData = new ArrayDeque<ByteBuffer>();
26
27         /**
28          * Assumes that the message is valid (that you cannot create an invalid
29          * message from API). Serializes given messages to byte array, converts this
30          * byte array to byteBuffer and adds it to List.
31          * @param message message to be written
32          * @param factory protocol specific message factory
33          */
34         public void putMessage(final ProtocolMessage message, final ProtocolMessageFactory factory) {
35                 final byte[] bytes = factory.put(message);
36                 if (bytes == null) {
37                         throw new IllegalArgumentException("Message parsed to null.");
38                 }
39                 synchronized (this.pendingData) {
40                         this.pendingData.add(ByteBuffer.wrap(bytes));
41                 }
42         }
43
44         /**
45          * Used by PCEPDispatcher to retrieve the data that needs to be written to
46          * socket.
47          *
48          * @return data that needs to be written to socket
49          */
50         Queue<ByteBuffer> getBuffers() {
51                 return this.pendingData;
52         }
53 }