View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.numbers.core;
19  
20  import java.io.ByteArrayInputStream;
21  import java.io.ByteArrayOutputStream;
22  import java.io.IOException;
23  import java.io.ObjectInputStream;
24  import java.io.ObjectOutputStream;
25  
26  /**
27   * Test utilities.
28   */
29  public final class TestUtils {
30      /**
31       * Collection of static methods used in math unit tests.
32       */
33      private TestUtils() {
34      }
35  
36      /**
37       * Serializes an object to a bytes array and then recovers the object from the bytes array.
38       * Returns the deserialized object.
39       *
40       * @param o  object to serialize and recover
41       * @return  the recovered, deserialized object
42       */
43      public static Object serializeAndRecover(Object o) {
44          try {
45              // serialize the Object
46              final ByteArrayOutputStream bos = new ByteArrayOutputStream();
47              final ObjectOutputStream so = new ObjectOutputStream(bos);
48              so.writeObject(o);
49  
50              // deserialize the Object
51              final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
52              final ObjectInputStream si = new ObjectInputStream(bis);
53              return si.readObject();
54          } catch (final IOException ioe) {
55              return null;
56          } catch (final ClassNotFoundException cnfe) {
57              return null;
58          }
59      }
60  }