| 1 | /* |
| 2 | * Copyright 2006-2010 the original author or authors. |
| 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 | package org.springframework.batch.support; |
| 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.io.OptionalDataException; |
| 24 | |
| 25 | |
| 26 | /** |
| 27 | * Static utility to help with serialization. |
| 28 | * |
| 29 | * @author Dave Syer |
| 30 | * |
| 31 | */ |
| 32 | public class SerializationUtils { |
| 33 | |
| 34 | /** |
| 35 | * Serialize the object provided. |
| 36 | * |
| 37 | * @param object the object to serialize |
| 38 | * @return an array of bytes representing the object in a portable fashion |
| 39 | */ |
| 40 | public static byte[] serialize(Object object) { |
| 41 | |
| 42 | if (object==null) { |
| 43 | return null; |
| 44 | } |
| 45 | |
| 46 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); |
| 47 | try { |
| 48 | new ObjectOutputStream(stream).writeObject(object); |
| 49 | } catch (IOException e) { |
| 50 | throw new IllegalArgumentException("Could not serialize object of type: "+object.getClass(), e); |
| 51 | } |
| 52 | |
| 53 | return stream.toByteArray(); |
| 54 | |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * @param bytes a serialized object created |
| 59 | * @return the result of deserializing the bytes |
| 60 | */ |
| 61 | public static Object deserialize(byte[] bytes) { |
| 62 | |
| 63 | if (bytes==null) { |
| 64 | return null; |
| 65 | } |
| 66 | |
| 67 | try { |
| 68 | return new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); |
| 69 | } |
| 70 | catch (OptionalDataException e) { |
| 71 | throw new IllegalArgumentException("Could not deserialize object: eof="+e.eof+ " at length="+e.length, e); |
| 72 | } |
| 73 | catch (IOException e) { |
| 74 | throw new IllegalArgumentException("Could not deserialize object", e); |
| 75 | } |
| 76 | catch (ClassNotFoundException e) { |
| 77 | throw new IllegalStateException("Could not deserialize object type", e); |
| 78 | } |
| 79 | |
| 80 | } |
| 81 | |
| 82 | } |