blob: 21425debdce6e1625c89c05a2d58ca43b7684af8 [file] [log] [blame]
Tomek OsiƄskie9ccf412018-01-13 19:44:11 +01001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.xmpp.core.ctl.handlers;
18
19
20import com.fasterxml.aalto.AsyncByteArrayFeeder;
21import com.fasterxml.aalto.AsyncXMLInputFactory;
22import com.fasterxml.aalto.AsyncXMLStreamReader;
23import com.fasterxml.aalto.stax.InputFactoryImpl;
24import io.netty.buffer.ByteBuf;
25import io.netty.channel.ChannelHandlerContext;
26import io.netty.handler.codec.ByteToMessageDecoder;
27import org.codehaus.stax2.ri.evt.Stax2EventAllocatorImpl;
28import org.dom4j.DocumentFactory;
29import org.slf4j.Logger;
30import org.slf4j.LoggerFactory;
31
32import javax.xml.stream.XMLStreamException;
33import java.util.List;
34
35/**
36 * Decodes a incoming data from XML stream.
37 */
38public class XmlStreamDecoder extends ByteToMessageDecoder {
39
40 private final Logger logger = LoggerFactory.getLogger(getClass());
41
42 private static final AsyncXMLInputFactory XML_INPUT_FACTORY = new InputFactoryImpl();
43 private Stax2EventAllocatorImpl allocator = new Stax2EventAllocatorImpl();
44 private AsyncXMLStreamReader<AsyncByteArrayFeeder> streamReader = XML_INPUT_FACTORY.createAsyncForByteArray();
45 private DocumentFactory df = DocumentFactory.getInstance();
46
47 @Override
48 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
49
50 AsyncByteArrayFeeder streamFeeder = streamReader.getInputFeeder();
51 logger.info("Decoding XMPP data.. ");
52
53 byte[] buffer = new byte[in.readableBytes()];
54 in.readBytes(buffer);
55 logger.debug("Buffer length: " + buffer.length);
56 try {
57 streamFeeder.feedInput(buffer, 0, buffer.length);
58 } catch (XMLStreamException exception) {
59 logger.info(exception.getMessage());
60 in.skipBytes(in.readableBytes());
61 logger.info("Bytes skipped");
62 throw exception;
63 }
64
65 while (streamReader.hasNext() && streamReader.next() != AsyncXMLStreamReader.EVENT_INCOMPLETE) {
66 out.add(allocator.allocate(streamReader));
67 }
68
69 }
70}