001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.fabric.netty.codec.serialization;
016    
017    import com.liferay.portal.kernel.io.AnnotatedObjectOutputStream;
018    
019    import io.netty.buffer.ByteBuf;
020    import io.netty.buffer.ByteBufOutputStream;
021    import io.netty.channel.ChannelHandler.Sharable;
022    import io.netty.channel.ChannelHandlerContext;
023    import io.netty.handler.codec.MessageToByteEncoder;
024    
025    import java.io.IOException;
026    import java.io.ObjectOutputStream;
027    import java.io.Serializable;
028    
029    /**
030     * @author Shuyang Zhou
031     */
032    @Sharable
033    public class AnnotatedObjectEncoder extends MessageToByteEncoder<Serializable> {
034    
035            public static final AnnotatedObjectEncoder INSTANCE =
036                    new AnnotatedObjectEncoder();
037    
038            public static final String NAME = AnnotatedObjectEncoder.class.getName();
039    
040            @Override
041            protected void encode(
042                            ChannelHandlerContext channelHandlerContext,
043                            Serializable serializable, ByteBuf byteBuf)
044                    throws IOException {
045    
046                    int startIndex = byteBuf.writerIndex();
047    
048                    ByteBufOutputStream byteBufOutputStream = new ByteBufOutputStream(
049                            byteBuf);
050    
051                    byteBufOutputStream.writeInt(0);
052    
053                    ObjectOutputStream objectOutputStream = new AnnotatedObjectOutputStream(
054                            byteBufOutputStream);
055    
056                    objectOutputStream.writeObject(serializable);
057    
058                    objectOutputStream.flush();
059    
060                    int endIndex = byteBuf.writerIndex();
061    
062                    byteBuf.setInt(startIndex, endIndex - startIndex - 4);
063            }
064    
065            private AnnotatedObjectEncoder() {
066            }
067    
068    }