1 /*
2 * Copyright 2012 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * https://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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty.handler.codec.serialization;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufOutputStream;
20 import io.netty.channel.ChannelHandler.Sharable;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.handler.codec.MessageToByteEncoder;
23
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
26 import java.io.Serializable;
27
28 /**
29 * An encoder which serializes a Java object into a {@link ByteBuf}.
30 * <p>
31 * Please note that the serialized form this encoder produces is not
32 * compatible with the standard {@link ObjectInputStream}. Please use
33 * {@link ObjectDecoder} or {@link ObjectDecoderInputStream} to ensure the
34 * interoperability with this encoder.
35 * <p>
36 * <strong>Security:</strong> serialization can be a security liability,
37 * and should not be used without defining a list of classes that are
38 * allowed to be desirialized. Such a list can be specified with the
39 * <tt>jdk.serialFilter</tt> system property, for instance.
40 * See the <a href="https://docs.oracle.com/en/java/javase/17/core/serialization-filtering1.html">
41 * serialization filtering</a> article for more information.
42 *
43 * @deprecated This class has been deprecated with no replacement,
44 * because serialization can be a security liability
45 */
46 @Deprecated
47 @Sharable
48 public class ObjectEncoder extends MessageToByteEncoder<Serializable> {
49 private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
50
51 public ObjectEncoder() {
52 super(Serializable.class);
53 }
54
55 @Override
56 protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
57 int startIdx = out.writerIndex();
58
59 ByteBufOutputStream bout = new ByteBufOutputStream(out);
60 ObjectOutputStream oout = null;
61 try {
62 bout.write(LENGTH_PLACEHOLDER);
63 oout = new CompactObjectOutputStream(bout);
64 oout.writeObject(msg);
65 oout.flush();
66 } finally {
67 if (oout != null) {
68 oout.close();
69 } else {
70 bout.close();
71 }
72 }
73
74 int endIdx = out.writerIndex();
75
76 out.setInt(startIdx, endIdx - startIdx - 4);
77 }
78 }