JDKRandom.java

  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. package org.apache.commons.rng.core.source32;

  18. import java.util.Random;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.ObjectOutputStream;
  22. import java.io.ObjectStreamClass;
  23. import java.io.ObjectInputStream;
  24. import java.io.ByteArrayOutputStream;

  25. import org.apache.commons.rng.core.util.NumberFactory;

  26. import java.io.ByteArrayInputStream;

  27. /**
  28.  * A provider that uses the {@link Random#nextInt()} method of the JDK's
  29.  * {@link Random} class as the source of randomness.
  30.  *
  31.  * <p>
  32.  * <b>Caveat:</b> All the other calls will be redirected to the methods
  33.  * implemented within this library.
  34.  * </p>
  35.  *
  36.  * <p>
  37.  * The state of this source of randomness is saved and restored through
  38.  * the serialization of the {@link Random} instance.
  39.  * </p>
  40.  *
  41.  * @since 1.0
  42.  */
  43. public class JDKRandom extends IntProvider {
  44.     /** Delegate.  Cannot be "final" (to allow serialization). */
  45.     private Random delegate;

  46.     /**
  47.      * An <code>ObjectInputStream</code> that's restricted to deserialize
  48.      * only {@link java.util.Random} using look-ahead deserialization.
  49.      *
  50.      * <p>Adapted from o.a.c.io.serialization.ValidatingObjectInputStream.</p>
  51.      *
  52.      * @see <a href="http://www.ibm.com/developerworks/library/se-lookahead/">
  53.      *  IBM DeveloperWorks Article: Look-ahead Java deserialization</a>
  54.      */
  55.     private static final class ValidatingObjectInputStream extends ObjectInputStream {
  56.         /**
  57.          * @param in Input stream
  58.          * @throws IOException Signals that an I/O exception has occurred.
  59.          */
  60.         ValidatingObjectInputStream(final InputStream in) throws IOException {
  61.             super(in);
  62.         }

  63.         /** {@inheritDoc} */
  64.         @Override
  65.         protected Class<?> resolveClass(final ObjectStreamClass osc) throws IOException,
  66.             ClassNotFoundException {
  67.             // For legacy reasons the Random class is serialized using only primitives
  68.             // even though modern implementations use AtomicLong.
  69.             // The only expected class is java.util.Random.
  70.             if (!Random.class.getName().equals(osc.getName())) {
  71.                 throw new IllegalStateException("Stream does not contain java.util.Random: " + osc.getName());
  72.             }
  73.             return super.resolveClass(osc);
  74.         }
  75.     }

  76.     /**
  77.      * Creates an instance with the given seed.
  78.      *
  79.      * @param seed Initial seed.
  80.      */
  81.     public JDKRandom(Long seed) {
  82.         delegate = new Random(seed);
  83.     }

  84.     /**
  85.      * {@inheritDoc}
  86.      *
  87.      * @see Random#nextInt()
  88.      */
  89.     @Override
  90.     public int next() {
  91.         return delegate.nextInt();
  92.     }

  93.     /** {@inheritDoc} */
  94.     @Override
  95.     protected byte[] getStateInternal() {
  96.         try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
  97.              ObjectOutputStream oos = new ObjectOutputStream(bos)) {

  98.             // Serialize the "delegate".
  99.             oos.writeObject(delegate);

  100.             final byte[] state = bos.toByteArray();
  101.             final int stateSize = state.length; // To allow state recovery.
  102.             // Compose the size with the state
  103.             final byte[] sizeAndState = composeStateInternal(NumberFactory.makeByteArray(stateSize),
  104.                                                              state);
  105.             return composeStateInternal(sizeAndState,
  106.                                         super.getStateInternal());
  107.         } catch (IOException e) {
  108.             // Workaround checked exception.
  109.             throw new IllegalStateException(e);
  110.         }
  111.     }

  112.     /** {@inheritDoc} */
  113.     @Override
  114.     protected void setStateInternal(byte[] s) {
  115.         // First obtain the state size
  116.         final byte[][] s2 = splitStateInternal(s, 4);
  117.         final int stateSize = NumberFactory.makeInt(s2[0]);

  118.         // Second obtain the state
  119.         final byte[][] c = splitStateInternal(s2[1], stateSize);

  120.         // Use look-ahead deserialization to validate the state byte[] contains java.util.Random.
  121.         try (ByteArrayInputStream bis = new ByteArrayInputStream(c[0]);
  122.              ObjectInputStream ois = new ValidatingObjectInputStream(bis)) {

  123.             delegate = (Random) ois.readObject();
  124.         } catch (ClassNotFoundException | IOException e) {
  125.             // Workaround checked exception.
  126.             throw new IllegalStateException(e);
  127.         }

  128.         super.setStateInternal(c[1]);
  129.     }
  130. }