Open Kilda Java Documentation
ByteArraySerializer.java
Go to the documentation of this file.
1 /* Copyright 2017 Telstra Open Source
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package org.openkilda.messaging;
17 
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.ObjectInputStream;
22 import java.io.ObjectOutputStream;
23 import java.nio.ByteBuffer;
24 
25 public interface ByteArraySerializer extends AbstractSerializer {
26  ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
27 
28  @Override
29  default Object deserialize() throws IOException, ClassNotFoundException {
30  ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer.array());
31  ObjectInputStream ois = new ObjectInputStream(bais);
32  Object obj = ois.readObject();
33  ois.close();
34  bais.close();
35  byteBuffer.clear();
36  return obj;
37  }
38 
39  @Override
40  default void serialize(Object obj) throws IOException {
41  ByteArrayOutputStream baos = new ByteArrayOutputStream();
42  ObjectOutputStream oos = new ObjectOutputStream(baos);
43  oos.writeObject(obj);
44  oos.flush();
45  byteBuffer.put(baos.toByteArray());
46  oos.close();
47  baos.close();
48  }
49 }